Way to get number of digits in an int?

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

    I see people using String libraries or even using the Integer class. Nothing wrong with that but the algorithm for getting the number of digits is not that complicated. I am using a long in this example but it works just as fine with an int.

     private static int getLength(long num) {
    
        int count = 1;
    
        while (num >= 10) {
            num = num / 10;
            count++;
        }
    
        return count;
    }
    

提交回复
热议问题