Way to get number of digits in an int?

后端 未结 30 1362
梦毁少年i
梦毁少年i 2020-11-22 17:21

Is there a neater way for getting the number of digits in an int than this method?

int numDigits = String.valueOf(1000).length();
30条回答
  •  鱼传尺愫
    2020-11-22 17:22

    We can achieve this using a recursive loop

        public static int digitCount(int numberInput, int i) {
            while (numberInput > 0) {
            i++;
            numberInput = numberInput / 10;
            digitCount(numberInput, i);
            }
            return i;
        }
    
        public static void printString() {
            int numberInput = 1234567;
            int digitCount = digitCount(numberInput, 0);
    
            System.out.println("Count of digit in ["+numberInput+"] is ["+digitCount+"]");
        }
    

提交回复
热议问题