Java judges how many digits an integer has

Java judges how many digits an integer has

First, encapsulate a method for judging the number of digits; use a for loop to judge the number of digits of an integer. Stop looping until the passed integer is less than a certain value in the array.

	/**
     * 获取整数有多少位
     * @param num 要判断的整数
     * @return 该整数的位数
     */
    public static int getNumDigit(int num) {
    
    
        // 设置整数最大位数组参数
        int[] digits = {
    
    9, 99, 999, 9999, 99999, 999999, 9999999,
                99999999, 999999999, Integer.MAX_VALUE};
        // 循环判断num的大小
        for (int i = 0; ; i++) {
    
    
            // 当num的值小于digits[i]时停止循环,此时i+1便是当前num的位数
            if (num <= digits[i]) {
    
    
                return i + 1;
            }
        }
    }

Test: Define a seven-digit number 1000000, and call the method to obtain the number of integer digits.

public static void main(String[] args) {
    
    
       int num = 1000000;
       int numDigit = getNumDigit(num);
       System.out.println(num + " 的位数是:" + numDigit);
}

Test results:
Test Results
hope to help you!

Guess you like

Origin blog.csdn.net/qq_42320934/article/details/122564877