Even 偶數;Odd 奇數
題目
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();