Skip to content

Commit 88bc5b4

Browse files
committed
feat(day 52): implement binary-to-decimal converter with validation and optimized version
1 parent 7fd8fc2 commit 88bc5b4

2 files changed

Lines changed: 62 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
Binary to Decimal
3+
Given a string representing a binary number, return its decimal equivalent as a number.
4+
5+
A binary number uses only the digits 0 and 1 to represent any number. To convert binary to decimal, multiply each digit by a power of 2 and add them together. Start by multiplying the rightmost digit by 2^0, the next digit to the left by 2^1, and so on. Once all digits have been multiplied by a power of 2, add the result together.
6+
7+
For example, the binary number 101 equals 5 in decimal because:
8+
9+
1 * 2^2 + 0 * 2^1 + 1 * 2^0 = 4 + 0 + 1 = 5
10+
"""
11+
12+
def to_decimal(binary):
13+
summ = 0
14+
15+
for index, num in enumerate(binary[::-1]):
16+
17+
summ += int(num) * 2 ** index
18+
19+
return summ
20+
21+
def to_decimal_another_way(binary):
22+
23+
decimal = 0
24+
for index, digit in enumerate(reversed(binary)):
25+
if digit not in '01':
26+
raise ValueError("Input must be a binary string containing only 0s and 1s.")
27+
decimal += int(digit) * (2 ** index)
28+
29+
return decimal
30+
31+
32+
def to_decimal_optimized(binary):
33+
34+
if not all(c in '01' for c in binary):
35+
raise ValueError("Input must be a binary string.")
36+
37+
return sum(int(num) * 2 ** i for i, num in enumerate(binary[::-1]))
38+
39+
40+
if __name__ == "__main__":
41+
print(to_decimal("101"))
42+
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import unittest
2+
from BinaryToDec import to_decimal
3+
4+
5+
class BinaryToDecTest(unittest.TestCase):
6+
7+
def test1(self):
8+
self.assertEqual(to_decimal("101"),5)
9+
10+
def test2(self):
11+
self.assertEqual(to_decimal("1010"),10)
12+
13+
def test3(self):
14+
self.assertEqual(to_decimal("10010"),18)
15+
16+
def test4(self):
17+
self.assertEqual(to_decimal("1010101"),85)
18+
19+
if __name__ == "__main__":
20+
unittest.main()

0 commit comments

Comments
 (0)