Explain Codes LogoExplain Codes Logo

Way to get the number of digits in an int?

java
performance
best-practices
mathematical-operations
Anton ShumikhinbyAnton Shumikhin·Jan 5, 2025
TLDR

To swiftly determine the digit count of an int:

int numDigits = (int) (Math.log10(Math.abs(yourInt)) + 1);

This one-liner leverages the power of Math.log10(), avoiding string conversion and applying direct digit count to absolutely positive integers.

Efficient computation: logarithm to the rescue

When it comes down to performance combat, mathematical operations often reign supreme over string manipulations. The beauty of this method lays in its ability to dodge memory overhead by skirting the integer-to-string conversion process.

Don't forget edge cases!

The logarithmic method exhibits proficiency until it encounters an adversary: 0. The mathematical law tells us log10(0) is undefined, rendering our method incapable. However, 0 has an obvious digit count: 1. Thus, we modify the code to account for 0:

int numDigits = (yourInt == 0) ? 1 : (int) (Math.log10(Math.abs(yourInt)) + 1);

Just remember, 0 has a digit count of 1, not . Infinity is the count of the number of times you were told to clean your room. 😉

Taking the string route

Sometimes, the best route is the most direct one. String conversion may not be memory efficient or the fastest method, but it's definitely simpler:

int numDigits = Integer.toString(Math.abs(yourInt)).length();

The Garbage Collector (GC) isn't pleased with this memory inefficiency, but hey, a little extra memory never hurt our bedroom floor, right?

Loop and conquer technique

The loop with division technique flexes its muscles with varying number ranges. By tuning the initial divisor to the expected number range, we engineer a performant loop:

int count = 0; for (int temp = Math.abs(yourInt); temp != 0; temp /= 10, ++count) {}

That's like counting the number of pizza slices by eating them! 🍕

Striking the balance: clarity vs performance

Maintaining a delicate balance between algorithm efficiency and code readability is crucial. An efficient divide-and-conquer approach risks clarity whereas a simple loop may appear aesthetically pleasing. Evaluate these trade-offs while determining the selection.

Get your pre-calculated size table out!

Intensify speed by utilizing a pre-defined sizeTable array, achieving rapid-fire digit calculation:

private static final int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE }; static int computeNumDigits(int x) { for (int i = 0;; i++) if (x <= sizeTable[i]) return i + 1; }

Don't play hide and seek with your digits, fetch them directly from the lookup table!

Performance analysis: testing your methods’ mettle

Benchmarking should be a staple in your code diet. To ensure accurate timing, start on a clean slate by triggering garbage collection prior to benchmarking.