Find the number of digits in a number. abs() is used as logarithm for negative numbers is not defined. >>> num_digits_fast(12345) 5 >>> num_digits_fast(123) 3 >>> num_digits_fast(0) 1 >>> num_digits_fast(-1) 1 >>> num_digits_fast(-123456) 6 >>> n
(n: int)
| 36 | |
| 37 | |
| 38 | def num_digits_fast(n: int) -> int: |
| 39 | """ |
| 40 | Find the number of digits in a number. |
| 41 | abs() is used as logarithm for negative numbers is not defined. |
| 42 | |
| 43 | >>> num_digits_fast(12345) |
| 44 | 5 |
| 45 | >>> num_digits_fast(123) |
| 46 | 3 |
| 47 | >>> num_digits_fast(0) |
| 48 | 1 |
| 49 | >>> num_digits_fast(-1) |
| 50 | 1 |
| 51 | >>> num_digits_fast(-123456) |
| 52 | 6 |
| 53 | >>> num_digits('123') # Raises a TypeError for non-integer input |
| 54 | Traceback (most recent call last): |
| 55 | ... |
| 56 | TypeError: Input must be an integer |
| 57 | """ |
| 58 | |
| 59 | if not isinstance(n, int): |
| 60 | raise TypeError("Input must be an integer") |
| 61 | |
| 62 | return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1) |
| 63 | |
| 64 | |
| 65 | def num_digits_faster(n: int) -> int: |