题目
Given an array nums
of integers, return how many of them contain an even number of digits.
给定一个整数数组nums,返回位数是偶数的数组元素的个数。
思路
关键:根据一位数整除10一次得0,二位数整除10两次得0,...,n位数整除10n次得0。
让每一个数组不断整除10直到变为0,每整除一次将其位数计数器digits+1。
实现代码
int findNumbers(int* nums, int numsSize){
int result = 0;
for (int i = 0; i <= numsSize - 1; i++) {
int temp_num = nums[i];
int temp_digits = 0;
while (temp_num > 0) {
temp_num /= 10;
temp_digits++;
}
if (temp_digits%2 == 0) {
result++;
}
}
return result;
}
坑
边界条件写成了“i <= numsSize”,结果报“Runtime Error”。把代码放进vscode跑,不会报错,但是跑的结果会不同。