Skip to content

Commit

Permalink
Create decimal_to_binary_converter.py
Browse files Browse the repository at this point in the history
  • Loading branch information
Kalpak Take authored Aug 20, 2017
1 parent f47f7f3 commit c033eaf
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions decimal_to_binary_converter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# For concatenation
def concat(S):
res = ""
for i in S:
if not isinstance(i, str):
res += str(i)
else:
res += i
return res

# Simple Base 10 number(Decimal) number converter to Base 2 number(binary) number
# Function returns answer in str datatype
# For understanding steps: http://www.electronics-tutorials.ws/binary/bin_2.html
def decimal_to_binary(n):
res = []
while n != 0:
res.append(n % 2)
n = n // 2
final = concat(res) + "0"
return final[::-1]


# Test
cases = [123, 23455, 253552, 87985, 3479434, 76, 246572, 231, 69, 2, 7, 2, 543]
for case in cases:
built_in = str(bin(case))[2:]
my_func = decimal_to_binary(case)[1:] # For test purposes
if built_in == my_func:
print("Decimal: " + str(case))
print("Binary: " + my_func + "\nTest Passed!\n")
else:
print("Test Failed! Badly!!\n")

0 comments on commit c033eaf

Please sign in to comment.