By Yingkai Lee


2020-03-26 02:33:11 8 Comments

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?

2 comments

@Joni 2020-03-26 02:52:32

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!

@Tim Biegeleisen 2020-03-26 02:36:10

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.

Related Questions

Sponsored Content

46 Answered Questions

[SOLVED] What does "Could not find or load main class" mean?

  • 2013-08-07 03:02:46
  • Stephen C
  • 2639249 View
  • 1336 Score
  • 46 Answer
  • Tags:   java class main

4 Answered Questions

[SOLVED] Finding Number of Cores in Java

  • 2011-01-21 13:54:49
  • Damir
  • 133509 View
  • 406 Score
  • 4 Answer
  • Tags:   java

18 Answered Questions

[SOLVED] What are the effects of exceptions on performance in Java?

31 Answered Questions

[SOLVED] How to round a number to n decimal places in Java

28 Answered Questions

[SOLVED] Way to get number of digits in an int?

  • 2009-08-20 14:51:55
  • fnst
  • 542229 View
  • 379 Score
  • 28 Answer
  • Tags:   java int

5 Answered Questions

36 Answered Questions

16 Answered Questions

[SOLVED] Why doesn't Java support unsigned ints?

45 Answered Questions

[SOLVED] Android SDK installation doesn't find JDK

2 Answered Questions

[SOLVED] How to reduce a given number in a two digit number without recursion method in Java?

  • 2018-07-28 18:27:06
  • rahul khanna
  • 45 View
  • 0 Score
  • 2 Answer
  • Tags:   java

Sponsored Content