Not registered yet?
Register now! It is easy and done in 1 minute and gives you access to special discounts and much more!
By Yingkai Lee
I use two processes through which I determine the number of digits a number has.
given x is an int value
int digits = ("" + x).length();
int digits = 0;
while(x > 0)
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.