12. Count Digits in a Number
Given an integer, count how many digits it contains.
How It Works & Algorithmic Design
For a positive integer, repeatedly divide the number by 10:
- Handle
0as a special case because it contains one digit. - Convert negative values to their absolute value.
- Repeatedly divide by
10using integer division. - Increment the digit counter after every division.
- Stop when the number becomes
0.
Why This Approach Works Best
Each iteration removes one decimal digit. Therefore the time complexity is $O(d)$ where $d$ is the number of digits, with $O(1)$ space.
Example Walkthrough
Input
5832
The number contains four digits.
Division
5832 -> 583 -> 58 -> 5 -> 0
Each division by 10 removes the last digit.
Output
4
Four divisions were required.
Answer: Count digits
function countDigits(n) {
n = Math.abs(n);
if (n === 0) return 1;
let count = 0;
while (n > 0) {
n = Math.floor(n / 10);
count++;
}
return count;
}Repeatedly remove the last digit using division by 10.
Key Takeaways
Integer division by 10 removes the last decimal digit.
Zero must be handled separately because 0 contains one digit.
The algorithm uses constant auxiliary space.