Back to Practice Dashboard
Python BasicsEasy
Calculate the number of digits in an integer
Learn how to solve the 'Calculate the number of digits in an integer' problem. This detailed resource details brute force and optimized approaches.
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?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.