Fastest way to get number of digits on a number? [duplicate]

时光毁灭记忆、已成空白 提交于 2019-11-29 02:54:55

问题


I have do detect the amount of digits on a number. For example, 329586 has 6 digits.

What I done, is simply parsing the number to string, and getting the string length, like:

number.toString().length()

But, is there a fastest way to count digits on a number? I have to use this method several times, so I think using toString() can impact performance.

Thanks.


回答1:


Math.floor(Math.log10(number) + 1)
// or just (int) Math.log10(number) + 1

For example:

int number = 123456;
int length = (int) Math.log10(number) + 1;
System.out.println(length);

OUTPUT:

6



回答2:


how about this homebrewed solution:

int noOfDigit = 1;
while((n=n/10) != 0) ++noOfDigit;



回答3:


Try this :

Working Example

public class Main {
    public static void main(String[] args) {
        long num = -23;
        int digits = 0;
        if (num < 0) 
            num *= (-1);
        if (num < 10 && num >= 0)
            digits = 1;
        else {
            while(num > 0) {
                num /= 10;
                digits++;
            }
        }
        System.out.println("Digits: " +digits);
    }
}


来源:https://stackoverflow.com/questions/15587818/fastest-way-to-get-number-of-digits-on-a-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!