Skip to content

Commit fe98a30

Browse files
Refactor binary to decimal conversion function
Rewrote bin_to_decimal to use Python's built-in int(s, 2) instead of a manual loop that accumulates the decimal value digit by digit. The logic and doctests are unchanged. Also added a guard for "-" as input, which previously slipped past the empty-string check and raised an unhelpful ValueError about non-binary values.
1 parent 791deb4 commit fe98a30

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

conversions/binary_to_decimal.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
def bin_to_decimal(bin_string: str) -> int:
22
"""
3-
Convert a binary value to its decimal equivalent
3+
Convert a binary value to its decimal equivalent.
44
55
>>> bin_to_decimal("101")
66
5
@@ -24,20 +24,21 @@ def bin_to_decimal(bin_string: str) -> int:
2424
ValueError: Non-binary value was passed to the function
2525
"""
2626
bin_string = str(bin_string).strip()
27+
2728
if not bin_string:
2829
raise ValueError("Empty string was passed to the function")
30+
2931
is_negative = bin_string[0] == "-"
3032
if is_negative:
3133
bin_string = bin_string[1:]
32-
if not all(char in "01" for char in bin_string):
34+
35+
if not bin_string or not all(char in "01" for char in bin_string):
3336
raise ValueError("Non-binary value was passed to the function")
34-
decimal_number = 0
35-
for char in bin_string:
36-
decimal_number = 2 * decimal_number + int(char)
37-
return -decimal_number if is_negative else decimal_number
37+
38+
result = int(bin_string, 2)
39+
return -result if is_negative else result
3840

3941

4042
if __name__ == "__main__":
4143
from doctest import testmod
42-
4344
testmod()

0 commit comments

Comments
 (0)