Way to get number of digits in an int?

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

    How about plain old Mathematics? Divide by 10 until you reach 0.

    public static int getSize(long number) {
            int count = 0;
            while (number > 0) {
                count += 1;
                number = (number / 10);
            }
            return count;
        }
    

提交回复
热议问题