Walk into any technical interview and you’ll likely encounter a question that sounds deceptively simple: “How many digits are in this integer?” It’s a classic, but it’s also a trap. Many candidates immediately reach for the logarithm method, assuming it’s an $O(1)$ operation that solves everything. They don’t. Unless you’ve specifically handled the edge case where $N=0$ or the input is negative, your code will crash or return garbage. I’ve sat across the table from candidates who got hung up on exactly this.
If you’re searching for the specific "count digits gfg" problem, you’re in the right place. GeeksforGeeks (GFG) is a go-to resource for DSA practice, but their tutorials often present solutions in isolation. This guide goes further. We’ll break down five distinct ways to count digits in number across Python, C++, and Java, dissect the exact GFG variant "Count Total Digits," and give you the complexity analysis you need to defend your code choices in a real interview. This isn’t just about syntax; it’s about understanding why one algorithm is safer than another.
The 5 Algorithms to Count Digits in a Number
Before we write a single line of code, it’s worth appreciating why there are multiple ways to solve this. The "right" way depends on whether you are writing a safety-critical banking system or a quick script for a data analysis job. Let’s walk through the five most common approaches, starting with the one I recommend you know by heart.
Method 1: Iterative Loop (Integer Division)
This is the "boring" way, and honestly, the best way to start. The logic is straightforward: divide the number by 10, check if it’s zero, and repeat. Every division strips off the last digit. It’s intuitive, and it works for zero, positive, and negative integers (if you take the absolute value first).
In a 15-year career spanning C++ and Go, I’ve found that integer division is the most robust method because it relies on basic arithmetic rather than floating-point math or memory allocation.
Python
def count_digits_iterative(n):
n = abs(n)
if n == 0:
return 1 # Special case: 0 has 1 digit
count = 0
while n > 0:
count += 1
n //= 10
return count
C++
#include <cmath>
int count_digits_cxx(int n) {
n = std::abs(n);
if (n == 0) return 1;
int count = 0;
while (n > 0) {
count++;
n /= 10;
}
return count;
}
Java
public static int countDigitsJava(int n) {
n = Math.abs(n);
if (n == 0) return 1;
int count = 0;
while (n > 0) {
count++;
n /= 10;
}
return count;
}
The time complexity here is $O(\log_{10} N)$, which is essentially the number of digits. The space complexity is $O(1)$. It’s safe, it’s fast, and it requires no extra libraries.
Method 2: String Conversion
Sometimes, the most efficient code in a language isn’t the most efficient algorithm. In Python, for example, converting to a string is a highly optimized C-level operation. For a quick script, len(str(n)) is often the most readable choice.
The downside? You’re allocating memory for a new string object. For a single integer, this is negligible. For a loop processing a billion numbers, this memory overhead becomes a bottleneck. Also, if you forget to handle the negative sign, len("-123") returns 4, not 3. You have to strip the sign or take the absolute value before conversion.
Method 3: Logarithm Method (O(1) Claim)
This is the method that trips people up. The formula is $\text{floor}(\log_{10}(N)) + 1$. For positive integers greater than zero, this works in constant time, mathematically. It doesn’t iterate; it calculates.
Critical Warning: This fails for $N=0$. $\log_{10}(0)$ is undefined (or negative infinity in floating point), so the formula breaks. It also fails for negative numbers because the logarithm of a negative number is complex, not real.
If you use this method in an interview, I always advise you to say: "I’ll use the log method for performance, but I have to guard against zero and negatives."
Python
import math
def count_digits_log(n):
n = abs(n)
if n == 0:
return 1
# For very large integers, log10 might lose precision,
# but for standard 64-bit ints, it's fine.
return int(math.floor(math.log10(n))) + 1
C++
#include <cmath>
#include <cstdlib>
int count_digits_log_cpp(int n) {
n = std::abs(n);
if (n == 0) return 1;
// Ceil log10 can also work, but floor + 1 is standard
return static_cast<int>(std::floor(std::log10(n))) + 1;
}
Method 4: Recursion
Recursion is elegant, but in my experience, it’s rarely the right tool for a simple digit count unless the interviewer specifically asks for it. The base case is if n < 10: return 1. The recursive step is 1 + count_digits(n // 10).
The main issue is the call stack. For a 64-bit integer, you’d have ~19 stack frames. For a "big integer" with 10,000 digits, you might hit the stack overflow limit in languages like Java or C++. Python allows a higher recursion limit, but it’s still slower than an iterative loop due to function call overhead.
Method 5: Handling Edge Cases & Big Integers
This isn’t a separate algorithm, but it’s a necessary layer of logic you must apply to all the above.
- Zero: As mentioned, most methods fail or behave unexpectedly for 0 unless explicitly handled.
- Negatives: Always use
abs(n)orMath.abs(n)before counting, unless the problem explicitly asks for the sign to be counted (rare). - Overflow: In C++ and Java,
Integer.MIN_VALUEis a famous trap.abs(Integer.MIN_VALUE)overflows to a negative number. If you’re working with 32-bit integers, check for this specific value. In Python, big integers are arbitrary precision, so you’re safe, but the string conversion method might be the only fast way to handle a 10,000-digit number without O(log N) iterations.
GeeksforGeeks Specifics: Solving 'Count Total Digits'
This is where the "geeksforgeeks count digits" search query gets confusing. GFG has two distinct problems that people mix up.
Understanding the GFG Practice Problem Variant
Most tutorials discuss Count Digits in Number N, which is what we covered above: $O(\log N)$.
However, GFG’s popular practice problem is often Count Total Digits from 1 to N. This is a significantly harder problem. It asks: given $N=12$, how many digits are in the sequence 1, 2, ..., 12? (Answer: 1+1+1+...+1+2 = 12).
This requires a mathematical, segment-based approach. You calculate the contribution of 1-digit numbers (1-9), 2-digit numbers (10-99), and so on.
- 1-digit numbers (1-9): 9 numbers $\times$ 1 digit = 9 digits.
- 2-digit numbers (10-N): For each position, calculate how many times each digit appears.
This is a "range summation" problem, not a single-number property problem. If you’re looking at GFG code for "Count Total Digits," and it involves loops that calculate powers of 10 and segments, you’re looking at this variant, not the simple one.
Navigational Guide to GFG Resources
When you search "count digits gfg," you’ll likely find:
- "Count Digits in Number N" (Easy): The single integer problem we detailed.
- "Digits That Divide N" (Medium): A different problem entirely. It asks how many digits within N divide N evenly.
- "Count Total Digits from 1 to N" (Hard/Competitive): The range-based mathematical problem.
If you are preparing for competitive coding, focus on #3. For standard interviews, #1 is more common, but knowing #3 sets you apart. GFG’s video tutorials for the "Count Total Digits" problem are particularly good for visualizing the segment logic.
Complexity Analysis: Which Method Wins?
Let’s put this in perspective with a comparison. I like to think of it as the "Swiss Army Knife" vs. the "Laser" debate.
Time & Space Comparison Table
| Method | Time Complexity | Space Complexity | Edge Case Safety | Best For |
|---|---|---|---|---|
| Iterative Loop | $O(\log N)$ | $O(1)$ | High (Handles 0, neg) | General purpose, C++/Java |
| Logarithm | $O(1)*$ | $O(1)$ | Low (Fails on 0, neg) | Performance-critical positive ints |
| String Conversion | $O(N)$ | $O(N)$ | Medium (Need abs) | Readability, Python, Big Ints |
| Recursion | $O(\log N)$ | $O(\log N)$ | Medium (Stack overflow) | Educational, functional styles |
| Segment Math | $O(\log N)$ | $O(1)$ | High | Range counting (1 to N) |
| $O(1)$ assumes fixed-precision floating point. For arbitrary precision, it’s $O(\log N)$. |
In my experience, the iterative loop is the "safe default." The log method is the "optimization." If an interviewer asks for the most efficient way to count digits in a number for a positive integer in a tight loop, the log method wins on CPU cycles. But if they ask for a robust function, the iterative loop wins.
Interview Strategy: What Candidates Prefer
Here’s my advice based on watching hundreds of interviews:
- Start Simple: "I can do this with a loop, dividing by 10. That’s $O(\log N)$."
- Mention the Edge Case: "I’d handle $N=0$ explicitly."
- Propose Optimization: "If we’re in a performance-critical environment and we know $N > 0$, I can use $\text{floor}(\log_{10} N) + 1$ which is $O(1)$."
- The "Lazy" Fallback: "In Python, I might just do
len(str(n))because string conversion is highly optimized in the C implementation and it’s readable."
This three-part answer shows you understand complexity, safety, and language-specific idioms. It’s a far better answer than just dumping one method.
Advanced Variants: Beyond Simple Counting
Once you’ve mastered the basics, these are the variants that appear in Medium/Hard interview rounds.
Count Digit Groupings
This is different from counting the length of a number. It’s counting how many times a specific digit appears.
- Example: Count the number of times the digit '1' appears in the range 1 to 13. (1, 10, 11, 12, 13).
- Logic: This requires a positional analysis. You look at the ones place, tens place, etc. This is a classic problem similar to "Number of 1 Bits" but expanded to decimal digits. It’s significantly harder than simple length counting because you have to handle overlaps (like the '1' in "11" counting for both the tens and ones place).
Digits That Divide N
- Problem: Given $N$, count how many digits in $N$ divide $N$ evenly.
- Example: $N = 12$. Digits are 1 and 2. 1 divides 12 (yes), 2 divides 12 (yes). Count = 2.
- Example: $N = 35$. Digits are 3 and 5. 3 does not divide 35. 5 divides 35. Count = 1.
- Edge Case: Digit 0. 0 cannot be a divisor. Always skip it.
Here’s a quick Java snippet for this variant, as it’s a common "count digits in number java code" question:
static int countDividingDigits(int n) {
int originalN = n;
int count = 0;
while (n > 0) {
int digit = n % 10;
if (digit != 0 && originalN % digit == 0) {
count++;
}
n /= 10;
}
return count;
}
Note how we separate originalN (the number to be divided) from n (the number being stripped of digits). This is a subtle bug source that many miss.
Frequently Asked Questions
What is the time complexity of counting digits in a number using logarithms?
Technically, for standard 64-bit integers, it’s $O(1)$ because log10 is a hardware-supported floating-point operation. However, if you are working with "big integers" (arbitrary precision) in Python or Java, the complexity scales with the number of digits, making it $O(\log N)$. Also, remember the $N=0$ failure mode.
How to count digits in a number without converting it to a string in Python? You have two main options:
-
Iterative Division:
def count(n): n = abs(n) if n == 0: return 1 count = 0 while n: n //= 10 count += 1 return count -
Logarithm:
import math def count(n): if n == 0: return 1 return int(math.log10(abs(n))) + 1
Is the GeeksforGeeks 'Count Total Digits' problem the same as counting digits in a single number? No. "Count Digits in Number N" is about the length of N ($O(\log N)$). "Count Total Digits from 1 to N" is about the sum of digits in all numbers up to N. The latter requires a segment-based mathematical formula and is a much harder problem, often found in competitive coding contests.
Conclusion
When you’re coding in production, I always recommend the iterative loop for its robustness. It handles zero, it handles negatives (with abs), and it doesn’t rely on floating-point precision. Save the logarithm method for specific performance bottlenecks where you’ve verified the input is strictly positive. Use string conversion when readability matters more than raw speed, especially in Python.
But the real takeaway? Understand the difference between "how long is this number?" and "how many digits are in the sequence 1 to N?" The GFG resources cover both, and conflating them is a common interview mistake.
For your next interview prep session, I’d suggest trying the "Digits That Divide N" variant. It forces you to think about modulo arithmetic and edge cases (like zero) more deeply than simple counting. And if you want to test your mathematical logic, tackle the "Count Total Digits from 1 to N" problem on LeetCode or GFG. It’s a great way to sharpen your ability to derive formulas on the fly.





