mathematics
programming
number theory
integer
digit count

Finding the number of digits of an integer

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Counting the number of digits in an integer is a common task in programming challenges, input validation, and number formatting. There are three standard approaches: converting to a string and measuring its length, using logarithms for a mathematical solution, and dividing by 10 in a loop. Each method has different performance characteristics and edge cases around zero and negative numbers.

Method 1: String Conversion

The simplest approach — convert the number to a string and count characters:

python
1def digit_count(n):
2    return len(str(abs(n)))
3
4print(digit_count(12345))   # 5
5print(digit_count(-9876))   # 4
6print(digit_count(0))       # 1
javascript
1function digitCount(n) {
2    return Math.abs(n).toString().length;
3}
4
5console.log(digitCount(12345));  // 5
6console.log(digitCount(-9876));  // 4
7console.log(digitCount(0));      // 1
java
public static int digitCount(int n) {
    return String.valueOf(Math.abs(n)).length();
}

This method is readable and handles zero and negatives naturally. The trade-off is that it allocates a string, which is slower than pure arithmetic for performance-critical code.

Method 2: Logarithm (Base 10)

The number of digits in a positive integer n is floor(log10(n)) + 1:

python
1import math
2
3def digit_count(n):
4    if n == 0:
5        return 1
6    return math.floor(math.log10(abs(n))) + 1
7
8print(digit_count(12345))   # 5
9print(digit_count(99))      # 2
10print(digit_count(100))     # 3
11print(digit_count(0))       # 1
javascript
1function digitCount(n) {
2    if (n === 0) return 1;
3    return Math.floor(Math.log10(Math.abs(n))) + 1;
4}
java
1public static int digitCount(int n) {
2    if (n == 0) return 1;
3    return (int) Math.floor(Math.log10(Math.abs(n))) + 1;
4}

The math behind this: log10(1000) = 3, so a 4-digit number like 1000 has floor(3) + 1 = 4 digits. This runs in O(1) time with no memory allocation.

Method 3: Repeated Division

Divide by 10 until the number reaches zero, counting iterations:

python
1def digit_count(n):
2    if n == 0:
3        return 1
4    n = abs(n)
5    count = 0
6    while n > 0:
7        n //= 10
8        count += 1
9    return count
10
11print(digit_count(12345))   # 5
12print(digit_count(0))       # 1
13print(digit_count(-42))     # 2
c
1int digit_count(int n) {
2    if (n == 0) return 1;
3    if (n < 0) n = -n;
4    int count = 0;
5    while (n > 0) {
6        n /= 10;
7        count++;
8    }
9    return count;
10}
java
1public static int digitCount(int n) {
2    if (n == 0) return 1;
3    n = Math.abs(n);
4    int count = 0;
5    while (n > 0) {
6        n /= 10;
7        count++;
8    }
9    return count;
10}

This is O(d) where d is the number of digits. It avoids floating-point issues entirely and works reliably with any integer size.

Method 4: Lookup Table (Fastest for Fixed-Width Integers)

For 32-bit integers, a precomputed table avoids both loops and floating-point math:

python
1def digit_count_32bit(n):
2    if n == 0:
3        return 1
4    n = abs(n)
5    thresholds = [
6        10, 100, 1000, 10000, 100000,
7        1000000, 10000000, 100000000,
8        1000000000, 10000000000
9    ]
10    for i, t in enumerate(thresholds, 1):
11        if n < t:
12            return i
13    return 10  # max digits for 32-bit int

This runs in constant time (at most 10 comparisons for a 32-bit integer) with no floating-point operations.

Comparison of Methods

MethodTime ComplexityHandles ZeroHandles NegativesFloating-Point Issues
String conversionO(d)YesUse abs()None
LogarithmO(1)Special caseUse abs()Possible at boundaries
Division loopO(d)Special caseUse abs()None
Lookup tableO(1)Special caseUse abs()None

Handling Edge Cases

python
1import math
2
3# Zero must be handled separately for log and division methods
4digit_count(0)  # Always returns 1
5
6# Negative numbers — use absolute value
7digit_count(-12345)  # 5, not 6 (don't count the minus sign)
8
9# Powers of 10 — the log method is susceptible to floating-point errors
10n = 10**15
11math.log10(n)  # Should be 15.0 but might be 14.999999999999998
12# Fix: use integer comparison
13int(math.log10(n))  # May give 14 instead of 15
14
15# Very large integers (Python handles arbitrary precision)
16digit_count(10**100)  # 101 — works with string and division methods
17# math.log10(10**100) — may overflow in languages with fixed-size floats

Language-Specific Notes

python
# Python: arbitrary precision integers, no overflow
len(str(10**1000))  # 1001 — works fine
java
1// Java: Integer.MIN_VALUE edge case
2// Math.abs(Integer.MIN_VALUE) is still negative (overflow)
3// Use long or handle separately
4int n = Integer.MIN_VALUE;  // -2147483648
5Math.abs(n);                // -2147483648 (not 2147483648!)
6String.valueOf(n).length() - 1;  // Correct: 10 digits
javascript
1// JavaScript: numbers are 64-bit floats
2// Integers above 2^53 - 1 lose precision
3Number.MAX_SAFE_INTEGER;  // 9007199254740991 (16 digits)
4// For larger numbers, use BigInt
5BigInt("99999999999999999").toString().length;  // 17

Common Pitfalls

  • Forgetting zero: log10(0) is negative infinity and a division loop on zero never executes. Both methods return incorrect results unless zero is handled as a special case (it has 1 digit).
  • Floating-point errors with logarithms: log10(1000) might return 2.9999999999999996 instead of 3.0, causing floor() to give 2 instead of 3. This happens at exact powers of 10 and varies by language and platform.
  • Integer overflow with abs(): In Java and C, abs(Integer.MIN_VALUE) overflows back to a negative number because the positive equivalent exceeds the max value. Use long or handle MIN_VALUE separately.
  • Counting the minus sign: str(-42) has length 3, but -42 has 2 digits. Always take the absolute value before counting.
  • Large integers and language limits: Python handles arbitrary-precision integers, but Java, C, and JavaScript have fixed-size integers. The string and division methods work across all sizes in Python, but the log method may overflow or lose precision in other languages.

Summary

  • String conversion (len(str(abs(n)))) is the simplest and most readable approach
  • Logarithm (floor(log10(abs(n))) + 1) is O(1) but has floating-point edge cases at powers of 10
  • Division loop (n //= 10 until zero) avoids floating-point issues and works with any integer size
  • Always handle zero as a special case (it has exactly 1 digit)
  • Use abs() to handle negative numbers, but watch for integer overflow in Java/C
  • For performance-critical code, a lookup table with threshold comparisons is the fastest approach

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.