Count Number of Digits in an Integer: 3 Methods
Three approaches to count digits in an integer: loop, recursion, and O(1) logarithm. Compare time complexity, edge cases, and what placement tests expect.
Three clean methods solve the count-digits problem: an iterative loop, a recursive call stack, and a constant-time logarithm formula.
Each approach reveals something different to a placement assessor. The loop shows you can reason about iteration. Recursion shows you understand the call stack and base cases. The logarithm formula shows mathematical intuition about how number systems are structured. Campus coding rounds at IT services companies will accept any of the three for a digit-counting question, then follow up with complexity or alternative-approach questions.
Why Placement Tests Use This Problem
Digit-counting appears in campus placement coding rounds because the problem is self-contained, has well-defined edge cases, and admits solutions at three different levels of sophistication. An assessor can evaluate a candidate’s depth just by watching which version they write first.
The string conversion answer, len(str(abs(n))) in Python, is the most common first response. It works and runs in O(d) time, where d is the number of digits. But it sidesteps the algorithmic reasoning the test is measuring. After a candidate writes the string version, interviewers at IT services companies typically ask for a solution that avoids string conversion. That request is where the loop and recursion approaches come in.
Understanding all three versions (including being able to discuss their trade-offs) matters for candidates sitting AMCAT-proctored assessments or company-specific online tests where coding clarity and complexity awareness are both scored. C coding practice questions covers the broader set of C coding patterns that appear in these rounds; digit-related problems are one recurring family in that set.
Two edge cases apply across all three methods. Handle them first, before writing the main logic:
- Negative integers: the sign is not a digit. Take
abs(n)at the start. - n = 0: return 1 immediately. Zero has exactly one digit. The loop body never executes for n=0, log10(0) is undefined, and the recursive base case needs to handle it explicitly.
Method 1: Count Digits Using a Loop
Divide the number by 10 repeatedly until nothing remains. Each division strips one digit from the right end of the number. The count of divisions equals the digit count.
def count_digits_loop(n):
n = abs(n) # handle negative numbers
if n == 0:
return 1 # 0 has exactly one digit
count = 0
while n != 0:
n //= 10
count += 1
return count
Trace through n = 5432:
- Start: n=5432, count=0
- Step 1: n=543, count=1
- Step 2: n=54, count=2
- Step 3: n=5, count=3
- Step 4: n=0, count=4
- Loop exits. Returns 4. Correct, 5432 has 4 digits.
Time complexity: O(d), where d is the number of digits. Space complexity: O(1), no auxiliary data structure needed.
The same logic works in C with a while (n != 0) loop and integer division. Placement tests at TCS, Wipro, and Cognizant often present digit problems in C rather than Python, so knowing both versions is worth the effort. The approach is structurally identical in both languages.
Method 2: Count Digits Using Recursion
The recursive method captures the same “strip one digit, count one step” logic as the loop, but uses the call stack instead of an explicit counter variable.
def count_digits_recursive(n):
n = abs(n)
if n < 10:
return 1 # base case: single-digit number
return 1 + count_digits_recursive(n // 10)
Trace through n = 5432:
count(5432)returns 1 +count(543)count(543)returns 1 +count(54)count(54)returns 1 +count(5)count(5)hits base case, returns 1- Unwind: 1 + 1 + 1 + 1 = 4. Correct.
For n = 0: abs(0) = 0, which satisfies n < 10, so the base case fires and returns 1. The edge case is handled without a separate guard.
Time complexity: O(d), same as the loop. Space complexity: O(d), because the call stack holds d activation frames simultaneously, one per digit. For a 10-digit integer, that is 10 frames, which is negligible.
If an interviewer asks about worst-case behaviour, mention that Python’s default recursion limit is 1000 frames (configurable via sys.setrecursionlimit). A number with 1001 digits would overflow the default stack. Placement test inputs never approach that threshold, but knowing the limit shows the assessor you’ve thought beyond the happy path.
The reduce-by-one-level recursion pattern here is the same structure that appears in Pascal’s Triangle program: each row computed from the previous one, each call reducing the problem by exactly one unit.
Method 3: Count Digits Using Logarithm
A d-digit positive integer n satisfies the inequality 10^(d-1) is less than or equal to n, which is less than 10^d. Taking the base-10 logarithm across that inequality gives d-1 is less than or equal to log10(n), which is less than d. Therefore d = floor(log10(n)) + 1.
import math
def count_digits_log(n):
if n == 0:
return 1 # log10(0) is undefined
return math.floor(math.log10(abs(n))) + 1
Spot-check the formula:
- n = 1: floor(log10(1)) + 1 = floor(0.0) + 1 = 0 + 1 = 1. Correct.
- n = 9: floor(log10(9)) + 1 = floor(0.954) + 1 = 0 + 1 = 1. Correct.
- n = 10: floor(log10(10)) + 1 = floor(1.0) + 1 = 1 + 1 = 2. Correct.
- n = 99: floor(log10(99)) + 1 = floor(1.996) + 1 = 1 + 1 = 2. Correct.
- n = 100: floor(log10(100)) + 1 = floor(2.0) + 1 = 2 + 1 = 3. Correct.
- n = 12345: floor(log10(12345)) + 1 = floor(4.091) + 1 = 4 + 1 = 5. Correct.
Time complexity: O(1). The mathematical library call runs in constant time regardless of the value of n. Space complexity: O(1).
The guard for n=0 is mandatory. Python’s math module raises a ValueError if you pass 0 to math.log10, because log10(0) is negative infinity in real-number arithmetic. Always add the explicit check before calling the function.
A floating-point precision caveat worth mentioning in interviews: for exact powers of 10 (n = 10, 100, 1000), the logarithm result is a clean integer and the formula works without ambiguity. For boundary values just below a power of 10, floating-point representation can produce a result like 1.9999… instead of 2.0, which floor would round down incorrectly. In practice, Python’s math.log10 handles standard integer inputs correctly. The GeeksforGeeks count-digits reference walks through the float-precision edge case with worked examples for those who want to see it in detail.
Comparing All Three Methods
| Method | Time | Space | Edge case: n=0 | Edge case: n < 0 |
|---|---|---|---|---|
| Loop | O(d) | O(1) | Explicit guard before loop | abs() at start |
| Recursion | O(d) | O(d) | Base case n < 10 covers it | abs() at start |
| Logarithm | O(1) | O(1) | Explicit guard required | abs() inside call |
In a placement test, the loop version is the default answer: clear to read and easy to explain step by step. When an interviewer says “rewrite it without a loop,” reach for recursion. When asked about O(1) time, explain the logarithm formula and note the floating-point precision caveat.
The digit-decomposition pattern (working on individual digits through repeated division or a mathematical identity) appears across a range of number problems. Multiplying a number by 111 is one example: the trick relies on how individual digit place values interact, which is exactly the same structural insight as stripping digits by dividing by 10.
The logarithm formula in Method 3 reduces d sequential divisions to a single constant-time call. That kind of derivation, identifying when a loop has a closed-form mathematical equivalent, is what distinguishes candidates who find algorithmic solutions from those who only translate problem statements to code. TinkerLLM at ₹299 is where FACE Prep recommends building that pattern-recognition: code-heavy exercises that ask you to derive and verify, not just implement.
Primary sources
Frequently asked questions
What is the digit count of the number 0?
Zero has exactly one digit. All three methods need a special check for n=0 because the loop exits immediately (while condition is false at entry), and log10(0) is undefined.
Do negative integers count differently?
No. The sign is not a digit. Take abs(n) before counting. The digit count of -12345 is 5, the same as 12345.
Which method should I use in a placement coding test?
Start with the loop method — clear to read and easy to explain step by step. If the interviewer asks for a non-loop solution, switch to recursion. Mention the logarithm formula when asked about O(1) time complexity.
Does Python's len(str(n)) work as a digit count solution?
Yes, it gives the correct answer and runs in O(d) time. Most placement evaluators accept it but will ask for a non-string version next, so knowing the loop method as a follow-up is important.
What is the time complexity of the logarithm method?
O(1) constant time. The math.log10 library call runs in fixed time regardless of how many digits the integer has. The loop and recursion methods both run in O(d) where d is the number of digits.
Can the recursion method cause a stack overflow for very large inputs?
In theory, yes. Each recursive call adds one frame to the stack, and Python's default recursion limit is 1,000 frames. A number with 1,001 digits would overflow it. In practice, placement test inputs stay well within this limit.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)