[英]How do I find the maximum one-digit integer in an array?
I am trying to find the maximum one-digit integer in an array.我试图在数组中找到最大的一位整数。
Let's say I have an array:假设我有一个数组:
[-6, -91, 1011, -100, 84, -22, 0, 1, 743]
The maximum integer is 1011
which I have found using:最大整数是
1011
我发现使用:
Math.max.apply(0,array)
But I need to find a maximum one-digit integer.但我需要找到一个最大的一位整数。 Is there any method to find it.
有什么方法可以找到。 The output should be
1
as per the above array.根据上述数组,输出应为
1
。
Math.max(...myArray.filter((n) => Math.abs(n) < 10))
You can use filter
to get single digits and Math.max to find maximum of single digist您可以使用
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.') }
I would just use reduce我只会使用减少
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)
moreover this falsy null
allows You to clearly define what You expect from that function when no integers in the {-9, 9} interval are found此外,当在 {-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] solution(A) A = [ -91, 1011, -100,184,0,-22, 473] 解(A)
Here is the simple C solution.这是简单的 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;
}
This can be achieved in php using the below这可以使用下面的 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.