Skip to content

Commit a56cb11

Browse files
committed
Fix digit count for powers of ten
1 parent 456d644 commit a56cb11

1 file changed

Lines changed: 12 additions & 3 deletions

File tree

maths/number_of_digits.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,17 @@ def num_digits_fast(n: int) -> int:
4444
5
4545
>>> num_digits_fast(123)
4646
3
47+
>>> num_digits_fast(1000)
48+
4
49+
>>> num_digits_fast(10**15)
50+
16
4751
>>> num_digits_fast(0)
4852
1
4953
>>> num_digits_fast(-1)
5054
1
5155
>>> num_digits_fast(-123456)
5256
6
53-
>>> num_digits('123') # Raises a TypeError for non-integer input
57+
>>> num_digits_fast('123') # Raises a TypeError for non-integer input
5458
Traceback (most recent call last):
5559
...
5660
TypeError: Input must be an integer
@@ -59,7 +63,12 @@ def num_digits_fast(n: int) -> int:
5963
if not isinstance(n, int):
6064
raise TypeError("Input must be an integer")
6165

62-
return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1)
66+
if n == 0:
67+
return 1
68+
69+
abs_n = abs(n)
70+
digits = math.floor(math.log10(abs_n)) + 1
71+
return digits + 1 if 10**digits <= abs_n else digits
6372

6473

6574
def num_digits_faster(n: int) -> int:
@@ -77,7 +86,7 @@ def num_digits_faster(n: int) -> int:
7786
1
7887
>>> num_digits_faster(-123456)
7988
6
80-
>>> num_digits('123') # Raises a TypeError for non-integer input
89+
>>> num_digits_faster('123') # Raises a TypeError for non-integer input
8190
Traceback (most recent call last):
8291
...
8392
TypeError: Input must be an integer

0 commit comments

Comments
 (0)