Skip to content

Commit d687030

Browse files
realDuYuanChaogithub-actions
and
github-actions
authored
fix number_of_digits bug (#2301)
* fix bug * test larger negative * fixup! Format Python code with psf/black push Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent aa46639 commit d687030

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

data_structures/binary_tree/basic_binary_tree.py

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ class Node:
55
"""
66
A Node has data variable and pointers to Nodes to its left and right.
77
"""
8+
89
def __init__(self, data: int) -> None:
910
self.data = data
1011
self.left: Optional[Node] = None

maths/number_of_digits.py

+26-2
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,20 @@ def num_digits(n: int) -> int:
1010
5
1111
>>> num_digits(123)
1212
3
13+
>>> num_digits(0)
14+
1
15+
>>> num_digits(-1)
16+
1
17+
>>> num_digits(-123456)
18+
6
1319
"""
1420
digits = 0
15-
while n > 0:
21+
n = abs(n)
22+
while True:
1623
n = n // 10
1724
digits += 1
25+
if n == 0:
26+
break
1827
return digits
1928

2029

@@ -27,8 +36,14 @@ def num_digits_fast(n: int) -> int:
2736
5
2837
>>> num_digits_fast(123)
2938
3
39+
>>> num_digits_fast(0)
40+
1
41+
>>> num_digits_fast(-1)
42+
1
43+
>>> num_digits_fast(-123456)
44+
6
3045
"""
31-
return math.floor(math.log(abs(n), 10) + 1)
46+
return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1)
3247

3348

3449
def num_digits_faster(n: int) -> int:
@@ -40,6 +55,12 @@ def num_digits_faster(n: int) -> int:
4055
5
4156
>>> num_digits_faster(123)
4257
3
58+
>>> num_digits_faster(0)
59+
1
60+
>>> num_digits_faster(-1)
61+
1
62+
>>> num_digits_faster(-123456)
63+
6
4364
"""
4465
return len(str(abs(n)))
4566

@@ -133,3 +154,6 @@ def benchmark() -> None:
133154
medium_num = 1125899906842624
134155
large_num = 1267650600228229401496703205376
135156
benchmark()
157+
import doctest
158+
159+
doctest.testmod()

0 commit comments

Comments
 (0)