In: Computer Science
Write a function decimalToBinary(n) that converts a positive decimal integer n to a string representing the corresponding binary number. Do the conversion by repeatedly dividing the number n by 2 using integer division, keepting track of the remainders, until the number is reduced to 0. The remainders written in reverse order form the binary number string.
Do integer division of 5 by 2, so that N//2 is 2 with remainder 1. Now divide 2 by 2 to get 1 with remainder 0. Next divide 1 by 2 to get 0 with remainder 1. Concatenating the remainders in reverse order makes 101, which is 5 in binary. Another example: N = 54. The division sequence is 54, 27, 13, 6, 3, 1, 0; and the remainder sequence is 0, 1, 1, 0, 1, 1. The remainders concatenated in reverse order produce: 110110, which is 54 in binary. Write a program which converts the values from 0 to 9 to binary, using the decimalToBinary(n) function. The output should look like:
0 is the binary of 0
1 is the binary of 1
10 is the binary of 2
11 is the binary of 3
100 is the binary of 4
101 is the binary of 5
110 is the binary of 6
111 is the binary of 7
1000 is the binary of 8
1001 is the binary of 9
Code is written in python
def decimalToBinary(n):
binary_num=[]
if(n==0):
return "0"
while (n > 0):
binary_num.append(str(n % 2));
n = n // 2;
return "".join(binary_num[::-1])
for i in range(10):
print(decimalToBinary(i)+" is the binary of "+str(i))