Count the Number of Digits in an Integer
Solve this ProblemEasy5 min
Topics
BasicsLoopsMath
Companies
TCSInfosysWipro
Given a non-negative integer
n, return how many digits it has.
The loopDivision LoopRepeatedly dividing by 10, counting divisions until the value reaches 0 — each division strips off exactly one digit. version is the classic numeric approach: it works the same way in every language and makes the "one digit per division" relationship explicit. The string conversionString ConversionConverting the number to its textual form and reading off its character count — the digit count falls out for free. version sidesteps the arithmetic entirely by treating digit-counting as a text problem instead.
Test Case 1:
Input:n = 1234
Output:4
Explanation:1234 has four digits.
Test Case 2:
Input:n = 0
Output:1
Explanation:Zero itself still counts as one digit.
Test Case 3:
Input:n = 7
Output:1
Explanation:A single digit.
Constraints
- ◆
0 ≤ n ≤ 1000000000
Try the Dry Run
Approach & Solutions
Loop — Divide by 10 Until ZeroGood
Repeatedly divide n by 10, counting how many divisions it takes to reach 0. Every division strips off one digit, so the number of divisions equals the number of digits. n = 0 is a special case — it has exactly one digit, but the loop would otherwise never run at all.
Time
O(d) — d is the number of digitsSpace
O(1)Java
1class Solution {
2 public int countDigits(int n) {
3 if (n == 0) {
4 return 1;
5 }
6 int count = 0;
7 while (n != 0) {
8 count++;
9 n = n / 10;
10 }
11 return count;
12 }
13}Using String ConversionOptimal
Convert n to its string representation and read off its length — the number of characters IS the number of digits. This also handles n = 0 correctly with no special case, since "0" is already a 1-character string.
Time
O(d)Space
O(d)Java
1class Solution {
2 public int countDigits(int n) {
3 return String.valueOf(n).length();
4 }
5}