[英]How do I find the maximum one-digit integer in an array?
我試圖在數組中找到最大的一位整數。
假設我有一個數組:
[-6, -91, 1011, -100, 84, -22, 0, 1, 743]
最大整數是1011
我發現使用:
Math.max.apply(0,array)
但我需要找到一個最大的一位整數。 有什么方法可以找到。 根據上述數組,輸出應為1
。
Math.max(...myArray.filter((n) => Math.abs(n) < 10))
您可以使用filter
來獲取個位數和 Math.max 來找到最大的個位數
let Arr = [-6, -91, 1011, -100, 84, -22, 0, 1, 743]; let singleDigits = Arr.filter(e => e >= -9 && e <= 9); if(singleDigits.length){ console.log(Math.max(...singleDigits)); }else{ console.log('there is no single digit number.') }
我只會使用減少
let Arr = [-6, -91, 1011, -100, 84, -22, 0, 1, 743];
const maxOneigit = Arr.reduce((acc, el) => {
return (el > -10 && el < 10 && el > acc) ? el : acc
}, null)
此外,當在 {-9, 9} 區間中找不到整數時,這個虛假的null
允許您清楚地定義您對該函數的期望
B_POS = []
C_NEG = []
C_NEG_Up = []
B_POS_Up = []
def solution(A):
A.sort()
print(A)
for j in A:
if j < 0:
C_NEG.append(j)
if (len(str(j)) == 2):
C_NEG_Up.append(j)
else:
B_POS.append(j)
if (len(str(j)) == 1):
B_POS_Up.append(j)
both = B_POS_Up + B_POS_Up
print(max(both,default = None))
A = [ -91, 1011, -100,184,0,-22, 473] 解(A)
這是簡單的 C 解決方案。
#include <stdio.h>
int find_max_single_digit(int arr[], int size) {
int result = 0;
for(int i = 0; i<size; i++) {
/*
* -9 to 9 will be single digit
*/
if (arr[i] > -10 && arr[i] < 10) {
if(arr[i] > result) {
result = arr[i];
}
}
}
return result;
}
int main()
{
int arr[]= {-6, -91, 1011, -100, 84, -22, 0, 1, 743};
int result = 0;
int size = sizeof(arr)/sizeof(arr[0]);
result = find_max_single_digit(arr, size);
printf("result = %d\n",result);
return 0;
}
這可以使用下面的 php 在 php 中實現
$num = [];
array_filter($data_array, function($n) use (&$num) {
if($n >= 1 && $n < 10) {
array_push($num, $n);
}
});
return (max($num));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.