I use two processes through which I determine the number of digits a number has.
given x is an int value
1.
int digits = ("" + x).length();
2.
int digits = 0;
while(x > 0)
{
digits ++;
x /= 10;
}
Why is the 2nd process usually faster?
Converting a number into a string is very similar to the division algorithm, but has more overhead because it has to create a string. Read the source code for Integer.toString
and you'll find a loop similar to your second process.
The second process is faster because the first process includes the second process!
The first method requires first converting the integer to a string, and then taking its length. There is an overhead involved in doing this conversion. On the other hand, the second version requires only division on the original integer. The division operation should generally be very fast, and can happen under the hood directly on the registers of the system which is running Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With