Find the number of digits in a number. >>> num_digits(12345) 5 >>> num_digits(123) 3 >>> num_digits(0) 1 >>> num_digits(-1) 1 >>> num_digits(-123456) 6 >>> num_digits('123') # Raises a TypeError for non-integer input Traceback (most recent call
(n: int)
| 3 | |
| 4 | |
| 5 | def num_digits(n: int) -> int: |
| 6 | """ |
| 7 | Find the number of digits in a number. |
| 8 | |
| 9 | >>> num_digits(12345) |
| 10 | 5 |
| 11 | >>> num_digits(123) |
| 12 | 3 |
| 13 | >>> num_digits(0) |
| 14 | 1 |
| 15 | >>> num_digits(-1) |
| 16 | 1 |
| 17 | >>> num_digits(-123456) |
| 18 | 6 |
| 19 | >>> num_digits('123') # Raises a TypeError for non-integer input |
| 20 | Traceback (most recent call last): |
| 21 | ... |
| 22 | TypeError: Input must be an integer |
| 23 | """ |
| 24 | |
| 25 | if not isinstance(n, int): |
| 26 | raise TypeError("Input must be an integer") |
| 27 | |
| 28 | digits = 0 |
| 29 | n = abs(n) |
| 30 | while True: |
| 31 | n = n // 10 |
| 32 | digits += 1 |
| 33 | if n == 0: |
| 34 | break |
| 35 | return digits |
| 36 | |
| 37 | |
| 38 | def num_digits_fast(n: int) -> int: |
nothing calls this directly
no outgoing calls
no test coverage detected