Skip to content

Commit 43cb60a

Browse files
committed
feat(day 53): add decimal-to_binary converter with reverse-build and optimized approach
1 parent 375e814 commit 43cb60a

2 files changed

Lines changed: 65 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
Decimal to Binary
3+
Given a non-negative integer, return its binary representation as a string.
4+
5+
A binary number uses only the digits 0 and 1 to represent any number. To convert a decimal number to binary, repeatedly divide the number by 2 and record the remainder. Repeat until the number is zero. Read the remainders last recorded to first. For example, to convert 12 to binary:
6+
7+
12 ÷ 2 = 6 remainder 0
8+
6 ÷ 2 = 3 remainder 0
9+
3 ÷ 2 = 1 remainder 1
10+
1 ÷ 2 = 0 remainder 1
11+
12 in binary is 1100.
12+
13+
"""
14+
15+
16+
def to_binary(decimal):
17+
binary = ""
18+
while decimal > 0:
19+
remainder = decimal % 2
20+
binary += str(remainder)
21+
decimal = decimal // 2
22+
23+
return binary[::-1]
24+
25+
26+
def to_binary_(decimal):
27+
28+
if decimal == 0:
29+
return '0'
30+
31+
binary = ''
32+
while decimal > 0:
33+
remainder = decimal % 2
34+
binary = str(remainder) + binary
35+
decimal = decimal // 2
36+
37+
return binary
38+
39+
if __name__ == "__main__":
40+
print(to_binary(5))
41+
print(to_binary(12))
42+
print(to_binary(50))
43+
print(to_binary(99))
44+
print(to_binary(0))
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import unittest
2+
from DecToBinary import to_binary
3+
4+
class DecToBinaryTest(unittest.TestCase):
5+
6+
def test1(self):
7+
self.assertEqual(to_binary(5),"101")
8+
9+
def test2(self):
10+
self.assertEqual(to_binary(12),"1100")
11+
12+
def test3(self):
13+
self.assertEqual(to_binary(50),"110010")
14+
15+
def test4(self):
16+
self.assertEqual(to_binary(99),"1100011")
17+
18+
19+
20+
if __name__ == "__main__":
21+
unittest.main()

0 commit comments

Comments
 (0)