Python BasicsEasy

Calculate the number of digits in an integer

Detailed guide and Python implementation for the 'Calculate the number of digits in an integer' problem.

Problem Statement

Easy

Write a function count_digits(n) that takes an integer n and returns the number of digits in its absolute value. For example, both 123 and -123 have 3 digits.

Note: The number 0 has 1 digit.

Constraints
  • -10^9 <= n <= 10^9

Examples

Example 1
Input
count_digits(12345)
Output
5
Explanation

12345 has digits 1, 2, 3, 4, 5 — that's 5 digits.

Example 2
Input
count_digits(-987)
Output
3
Explanation

Ignoring the sign, 987 has 3 digits.

Example 3
Input
count_digits(0)
Output
1
Explanation

The number 0 has exactly 1 digit.

Need a Hint?
Consider using Numbers-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.