Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions maths/number_of_digits.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,17 @@ def num_digits_fast(n: int) -> int:
5
>>> num_digits_fast(123)
3
>>> num_digits_fast(1000)
4
>>> num_digits_fast(10**15)
16
>>> num_digits_fast(0)
1
>>> num_digits_fast(-1)
1
>>> num_digits_fast(-123456)
6
>>> num_digits('123') # Raises a TypeError for non-integer input
>>> num_digits_fast('123') # Raises a TypeError for non-integer input
Traceback (most recent call last):
...
TypeError: Input must be an integer
Expand All @@ -59,7 +63,12 @@ def num_digits_fast(n: int) -> int:
if not isinstance(n, int):
raise TypeError("Input must be an integer")

return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1)
if n == 0:
return 1

abs_n = abs(n)
digits = math.floor(math.log10(abs_n)) + 1
return digits + 1 if 10**digits <= abs_n else digits


def num_digits_faster(n: int) -> int:
Expand All @@ -77,7 +86,7 @@ def num_digits_faster(n: int) -> int:
1
>>> num_digits_faster(-123456)
6
>>> num_digits('123') # Raises a TypeError for non-integer input
>>> num_digits_faster('123') # Raises a TypeError for non-integer input
Traceback (most recent call last):
...
TypeError: Input must be an integer
Expand Down