1295. 统计位数为偶数的数字『简单』

题目来源于力扣(LeetCode

一、题目

1295. 统计位数为偶数的数字

题目相关标签:数组

提示:

  • 1 <= nums.length <= 500
  • 1 <= nums[i] <= 10^5

二、解题思路

2.1 数学方式

  1. 利用题目给出的提示:1 <= nums[i] <= 10 ^ 5

  2. 其中 [10, 99],[1000, 9999],100000 中的数,其位数为偶数

2.2 字符串方式

  1. 遍历 nums 数组,对于每个元素转换成字符串操作

  2. 判断字符串长度是否为偶数,即被 2 整除

2.3 暴力法

  1. 遍历 nums 数组,对于每个元素都循环除 10,计算得到每个元素的位数

  2. 位数被 2 整除时,结果加 1

三、代码实现

3.1 数学方式

public static int findNumbers2(int[] nums) {
    int count = 0;
    for (int i : nums) {
        if (i >= 10 && i < 100) {
            // 10 ~ 99 的数字位数为2位
            count++;
        } else if (i >= 1000 && i < 10000) {
            // 1000 ~ 9999 的数字位数为4位
            count++;
        } else if (i == 100000) {
            // 100000 的数字位数为6位
            count++;
        }
    }
    return count;
}

3.2 字符串方式

public static int findNumbers(int[] nums) {
    int ans = 0;
    for (int num : nums) {
        String str = String.valueOf(num);
        if (str.length() % 2 == 0) {
            ans ++;
        }
    }
    return ans;
}

3.3 暴力法

public static int findNumbers(int[] nums) {
    int ans = 0;

    for (int i : nums) {
        int k = 0;
        // 循环计算数字 i 的位数
        while (i != 0) {
            i /= 10;
            k++;
        }
        // 位数为偶数时,count + 1
        if ((k & 1) == 0) {
            ans += 1;
        }
    }
    return ans;
}

四、执行用时

4.1 数学方式

4.2 字符串方式

4.3 暴力法

五、部分测试用例

public static void main(String[] args) {
    int[] nums = {12, 345, 2, 6, 7896};  // output: 2
//    int[] nums = {555, 901, 482, 1771};  // output: 1

    int result = findNumbers(nums);
    System.out.println(result);
}
原文地址:https://www.cnblogs.com/zhiyin1209/p/13170716.html