Best way to calculate the number of digits in Java



I found a way to calculate number of digits while learning DSA and here's it—


While solving numerous problems in DSA, I often found myself needing to count the digits of a number. Despite optimizing my solutions for the best possible output, my code still couldn't outperform many other solutions.

The underlying issue wasn't in the algorithm I wrote or the logic I built — it was in how I calculated the number of digits in my program.

Using a while loop was the biggest mistake I made. In terms of time complexity, it can cost you up to 4× more time than the most efficient solution available.

Now, you might be wondering:
What's the best way to count digits?

The answer is:

(int) Math.log10(num) + 1;


Concept Behind log10(num)

The base-10 logarithm tells you what power you need to raise 10 to in order to get that number.

For example:

log10(1000) = 3 → because 10³ = 1000

So in general:

log10(num) ≈ number of digits - 1

That’s why we use:

(int)(Math.log10(num)) + 1;


✅ Example

Let’s say num = 1234:

1. Math.log10(1234) ≈ 3.0913

2. (int) 3.0913 → 3

3. 3 + 1 → 4 digits


This gives us the correct number of digits.
And the best part? It's the fastest way to do it, with a time complexity of O(1).

Post a Comment

0 Comments