forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnum_digits.py
More file actions
39 lines (29 loc) · 693 Bytes
/
num_digits.py
File metadata and controls
39 lines (29 loc) · 693 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""
Number of Digits
Count the number of digits in an integer using logarithmic computation
for O(1) time complexity.
Reference: https://en.wikipedia.org/wiki/Logarithm
Complexity:
Time: O(1)
Space: O(1)
"""
from __future__ import annotations
import math
def num_digits(n: int) -> int:
"""Count the number of digits in an integer.
Args:
n: An integer (negative values use their absolute value).
Returns:
The number of digits in n.
Examples:
>>> num_digits(12)
2
>>> num_digits(0)
1
>>> num_digits(-254)
3
"""
n = abs(n)
if n == 0:
return 1
return int(math.log10(n)) + 1