Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed of finding the number of digits in a number

Tags:

java

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?

like image 336
Yingkai Lee Avatar asked Mar 02 '23 15:03

Yingkai Lee


2 Answers

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!

like image 96
Joni Avatar answered Mar 05 '23 16:03

Joni


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.

like image 20
Tim Biegeleisen Avatar answered Mar 05 '23 15:03

Tim Biegeleisen