Way to get number of digits in an int?

后端 未结 30 931
梦毁少年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:35

    no String API, no utils, no type conversion, just pure java iteration ->

    public static int getNumberOfDigits(int input) {
        int numOfDigits = 1;
        int base = 1;
        while (input >= base * 10) {
            base = base * 10;
            numOfDigits++;
        }
        return numOfDigits;
     }
    

    You can go long for bigger values if you please.

提交回复
热议问题