JavaScript Program to Count Digits in Number
number.toString().length or by repeatedly dividing the number by 10 and counting the steps.Examples
How to Think About It
Algorithm
Code
function countDigits(num) { num = Math.abs(num); if (num === 0) return 1; let count = 0; while (num > 0) { num = Math.floor(num / 10); count++; } return count; } console.log(countDigits(12345)); console.log(countDigits(0)); console.log(countDigits(-9876));
Dry Run
Let's trace counting digits in the number 12345 through the code
Start with number
num = 12345
Make positive
num = 12345 (already positive)
Check zero
num !== 0, continue
Initialize count
count = 0
Divide and count loop
num = Math.floor(12345 / 10) = 1234, count = 1
Next loop
num = Math.floor(1234 / 10) = 123, count = 2
Next loop
num = Math.floor(123 / 10) = 12, count = 3
Next loop
num = Math.floor(12 / 10) = 1, count = 4
Next loop
num = Math.floor(1 / 10) = 0, count = 5
Loop ends
num = 0, return count = 5
| num (after division) | count |
|---|---|
| 1234 | 1 |
| 123 | 2 |
| 12 | 3 |
| 1 | 4 |
| 0 | 5 |
Why This Works
Step 1: Convert to positive
Using Math.abs() ensures the number is positive so the minus sign doesn't affect digit count.
Step 2: Handle zero
Zero is a special case because it has one digit, so we return 1 immediately.
Step 3: Count digits by division
Dividing the number by 10 removes the last digit each time, so counting how many times we do this tells us the number of digits.
Alternative Approaches
function countDigits(num) { return num.toString().replace('-', '').length; } console.log(countDigits(12345)); console.log(countDigits(0)); console.log(countDigits(-9876));
function countDigits(num) { num = Math.abs(num); if (num === 0) return 1; return Math.floor(Math.log10(num)) + 1; } console.log(countDigits(12345)); console.log(countDigits(0)); console.log(countDigits(-9876));
Complexity: O(log n) time, O(1) space
Time Complexity
The loop divides the number by 10 each time, so it runs proportional to the number of digits, which is about log base 10 of the number.
Space Complexity
Only a few variables are used, so space is constant O(1).
Which Approach is Fastest?
The logarithm method is fastest for large numbers, string conversion is simplest, and division loop is easy to understand and reliable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Division loop | O(log n) | O(1) | Understanding and no string use |
| String conversion | O(n) | O(n) | Simplicity and readability |
| Logarithm | O(1) | O(1) | Performance with large numbers |
Math.abs() to handle negative numbers before counting digits.