Skip to content
Merged
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
24 changes: 24 additions & 0 deletions maths/number_of_digits.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,15 @@ def num_digits(n: int) -> int:
1
>>> num_digits(-123456)
6
>>> num_digits('123') # Raises a TypeError for non-integer input
Traceback (most recent call last):
...
TypeError: Input must be an integer
"""

if not isinstance(n, int):
raise TypeError("Input must be an integer")

digits = 0
n = abs(n)
while True:
Expand All @@ -42,7 +50,15 @@ def num_digits_fast(n: int) -> int:
1
>>> num_digits_fast(-123456)
6
>>> num_digits('123') # Raises a TypeError for non-integer input
Traceback (most recent call last):
...
TypeError: Input must be an integer
"""

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)


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

if not isinstance(n, int):
raise TypeError("Input must be an integer")

return len(str(abs(n)))


Expand Down