统计位数为偶数的数组的个数(Java)

示例:
输入:nums = [12,345,2,6,7896]
输出:2
解释:
12 是 2 位数字(位数为偶数)
345 是 3 位数字(位数为奇数)
2 是 1 位数字(位数为奇数)
6 是 1 位数字 位数为奇数)
7896 是 4 位数字(位数为偶数)
因此只有 12 和 7896 是位数为偶数的数字

import java.lang.reflect.Array;

/**
 * @author Think
 */
public class Test {
    
    

    public static void main(String[] args) {
    
    

        int[] nums = {
    
    12, 345, 2, 6, 7896};

        int numbers = findNumbers(nums);
        System.out.println("结果为:"+numbers);
    }

    /**
     * 解题思路在于把数字元素转成字符串数组,
     * 再判断其长度为偶数即可
     *
     * @param nums
     * @return
     */
    public static int findNumbers(int[] nums) {
    
    

        int n = 0;

        for (int i = 0; i < nums.length; i++) {
    
    

            String res = nums[i] + "";

            if (res.length() % 2 == 0) {
    
    
                n++;
            }
        }
        return n;

    }
}

猜你喜欢

转载自blog.csdn.net/qq_44739706/article/details/109473599