Open carloscn opened 1 year ago
快速判断位数,除法非常慢,有的人还要转换字符串占用空间。我们这样做,做一个比较数组,看在哪个范围内。
sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
fn is_even(e:i32) -> bool
{
let size_table:Vec<i32> =
vec![9, 99, 999, 9999, 99999,
999999, 9999999, 99999999,
999999999, i32::max_value()];
let mut count = 0;
for x in &size_table {
count += 1;
if e <= *x {
break;
}
}
return (count & 0x1) == 0;
}
pub fn find_numbers(nums: Vec<i32>) -> i32
{
let mut ret:i32 = 0;
if nums.len() < 1 {
return ret;
}
for e in nums {
if is_even(e) {
ret += 1;
}
}
return ret;
}
问题描述
给你一个整数数组 nums,请你返回其中位数为 偶数 的数字的个数。
示例 1:
输入:nums = [12,345,2,6,7896] 输出:2 解释: 12 是 2 位数字(位数为偶数) 345 是 3 位数字(位数为奇数) 2 是 1 位数字(位数为奇数) 6 是 1 位数字 位数为奇数) 7896 是 4 位数字(位数为偶数) 因此只有 12 和 7896 是位数为偶数的数字
示例 2:
输入:nums = [555,901,482,1771] 输出:1 解释: 只有 1771 是位数为偶数的数字。
提示:
1 <= nums.length <= 500 1 <= nums[i] <= 10^5
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/find-numbers-with-even-number-of-digits