FOR FREE CONTENT

Decimal to Binary

Back to Programming

Description

The program is written here to convert the decimal to binary. The decimal number is taken as input. The decimal number is divided by 2, then the quotient is again divided by 2 and this process repeats until the number becomes 0.

For example let the input be 45.

The binary equivalent of 45 is (101101)2

Algorithm

INPUT: Decimal Number

OUTPUT: Equivalent Binary Number

PROCESS:

Step 1: [Taking the inputs]

               Read n [The decimal number]

Step 2: [Converting from decimal number to binary number]

               Set binary=Null [A string to store the binary number]

While n>0 repeat

               Set c<-n mod 2

                              Concatenate the value of the variable ‘c’ with the string ‘binary’ in reversed order

                              Set n<-n/2

               [End of ‘while’ loop]

[Printing the binary number]

               Print "The binary number is: binary”

Step 3: Stop.

Code

TIME COMPLEXITY:

while(n>0)------------------------------------------------O(logn)

               {

                              binary[i++]=(char)(n%2+48);

                              n=n/2;

               }

 

The time complexity of converting a number from decimal to binary is O(log n) where n is the decimal number.

SPACE COMPLEXITY:

The space complexity of this algorithm is O(1) as it requires a constant number of memory spaces to execute the program for any given input.