easy +8 pts

Digit Count

Count the digits in an integer, handling negatives and zero, without converting to string.

Write a function `count_digits(n: int) -> int` that returns the number of digits in the integer `n` without converting `n` to a string. Handle negative numbers by ignoring the sign (e.g., -123 has 3 digits). For `n = 0`, return 1. The input `n` will be in the range [-10^9, 10^9]. The function should use arithmetic operations only — do not use `str()`, `repr()`, f-strings, or any string-based methods.

Constraints

-10^9 <= n <= 10^9, the function must run in O(number of digits) time and O(1) space.

Example

>>> count_digits(12345)
5
>>> count_digits(-9876)
4
>>> count_digits(0)
1
>>> count_digits(1000)
4
8 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think about repeatedly removing the last digit using integer division by 10.
Use a loop that counts iterations until the number becomes 0.
Be careful with negative numbers — you can take the absolute value first.
Handle the special case when n is zero separately.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.