Q3. Decimal To Binary
Q3. Decimal To Binary
Problem Description: Given a decimal number (integer N),you have to convert it into binary
and print it. The binary number should be printed in the form of an integer.
For example, if the given decimal number is 12,then the corresponding binary number will be
1100, and we need to print it.
How to approach?
A decimal number can be converted into a binary number by picking up the number and then
taking its remainder, after dividing it by 2, then start adding up the remainder by multiplying it
by its place value to convert the binary representation into an integer.
For example in case of 12, start picking up the remainder when 12 is divided by 2 and then
adding it by multiplying by its place value.
12 = 12%2 = 0*1 = 0
12/2 = 6%2 = 0*10 = 0
6/2 = 3%2 = 1*100 = 100
3/2 = 1%2 = 1*1000 = 1000
1/2 = 0. We will terminate the algorithm, when number becomes 0.
So, decimal number = 1000+100+0+0 = 1100
● rem=12%2=0
binary_number=0*1=0
pv=1*10=10
number=12/2=6.
● rem=6%2=0
binary_number=0+0*10=0
pv=10*10=100
number=6/2=3.
● rem=3%2=1
binary_number=0+1*100=100
pv=100*10=1000
number=3/2=1.
● rem=1%2=1
binary_number=100+1*1000=1100
pv=1000*10=10000
number=½=0