carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1295:统计位数为偶数的数字(find-numbers-with-even-number-of-digits) #202

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个整数数组 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

carloscn commented 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;
}
carloscn commented 1 year ago

code

https://github.com/carloscn/structstudy/commit/7446486af6704498349ca0b38e49885256585cbf https://review.gerrithub.io/c/carloscn/structstudy/+/553237