Programming
Number Theory
Integer Operations
Coding Tips
Algorithm Development

Way to get number of digits in an int?

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 digits in an integer is simple, but the best method depends on what you value most: clarity, speed, or avoiding conversions. The key edge cases are 0 and negative numbers, because both break naive solutions if you forget to handle them explicitly.

The Easiest Method: Convert to String

For most application code, the clearest answer is:

python
1def digit_count_string(n: int) -> int:
2    return len(str(abs(n)))
3
4
5print(digit_count_string(12345))
6print(digit_count_string(-98))
7print(digit_count_string(0))

This is easy to read and works well in high-level languages. The call to abs removes the minus sign from negative numbers.

The only special case is 0, which still works because str(0) is "0".

That is one reason the string approach remains popular: the edge cases are handled naturally with almost no extra code. It is also the easiest version for another developer to recognize immediately in a code review. That clarity matters more often than people think. Maintainability is part of correctness too. That is why it is often the best default answer.

The Arithmetic Method

If you want a numeric approach without string conversion, divide repeatedly by 10:

python
1def digit_count_loop(n: int) -> int:
2    n = abs(n)
3    if n == 0:
4        return 1
5
6    count = 0
7    while n > 0:
8        n //= 10
9        count += 1
10    return count
11
12
13print(digit_count_loop(12345))
14print(digit_count_loop(-98))
15print(digit_count_loop(0))

This is a good fit for lower-level environments or situations where you want to stay in arithmetic logic.

The Logarithm Formula

For positive integers:

text
digits = floor(log10(n)) + 1

Python example:

python
1import math
2
3def digit_count_log(n: int) -> int:
4    n = abs(n)
5    if n == 0:
6        return 1
7    return math.floor(math.log10(n)) + 1

This is concise, but it depends on floating-point math, so it is not always the best first choice if a simple string or loop solution would do.

Which Method Should You Use

Use string conversion when:

  • readability matters most
  • performance is not a hot-path concern
  • you are writing ordinary application code

Use the loop when:

  • you want a pure integer approach
  • you are in a language or environment where string conversion is undesirable

Use the logarithm formula when:

  • you want the mathematical shortcut
  • you are comfortable handling 0 as a special case

For most real code, the string method is the most maintainable answer.

If you are inside a tight numeric loop in a systems context, the arithmetic method may be more appropriate. But outside of those cases, readability usually matters more than shaving a tiny constant factor.

Language-Neutral Idea

The same concepts apply in other languages:

  • Java: String.valueOf(Math.abs(n)).length()
  • C#: Math.Abs(n).ToString().Length
  • C or C++: loop division or logarithm

The algorithmic choice is the same even if the syntax changes.

Common Pitfalls

The biggest mistake is forgetting that 0 has one digit. Any logarithm-based or loop-based method needs an explicit check for it.

Another mistake is ignoring negative numbers. If you convert directly to a string without removing the sign, the minus character gets counted too.

A third issue is over-optimizing. In many applications, a clear string-based solution is better than a mathematically clever one that is harder to read.

Summary

  • The simplest approach is string conversion plus length.
  • Arithmetic division by 10 is a clean no-string alternative.
  • The logarithm formula works, but needs special handling for 0.
  • Always account for negative numbers explicitly.
  • For normal application code, clarity usually beats micro-optimization here.

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.