关注 每天一道编程题 专栏,一起学习进步。
题目
Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.
Example 2:
Input: nums = [555,901,482,1771]
Output: 1
Explanation:
Only 1771 contains an even number of digits.
Constraints:
1 <= nums.length <= 500
1 <= nums[i] <= 10^5
分析
给一串数组,返回里面位数为偶数的数据个数。
就是
判断“移动多少位小数点使其小于0”
==>判断除以多少次“10”能使其小于0
解答
class Solution {
public int findNumbers(int[] nums) {
int result=0;
for(int num:nums){
int sum=0;
while(num>0){
num/=10;
sum++;
}
if(sum%2==0)
result++;
}
return result;
}
}
其他答案
更新奇
题目中已经给出限制:
1 <= nums[i] <= 10^5
也就是说:
10~99—偶数位
1000~9999—偶数位置
100000 —偶数位置
因此,只需要遍历nums,判断num是否在上述两个区间之内或等于100000即可。
Nice, telling myself to pay attention to constraints.
更简洁
将数字转为String,看他的长度是否为偶数
int result=0;
for(int n: nums){
result+= 1 - Integer.toString(n).lenght()%2;
return result;
由于取余结果要么为1(奇数),要么为0(偶数)
因此用1-取余结果
升级版
既然需要遍历,自然想到用Stream
return Arrays.stream(nums).map(i->1-Integer.toString(i).length()%2).sum();