The binary number is taken as input from the user. The decimal number can be calculated by adding the products of each digit and the power of 2 starting from 0 from the right to left.
For example, the binary number is 101101.
The decimal number will be:
= 32 + 0 + 8 + 4 + 0 + 1 = 45.
The value 45 will be printed.
INPUT: The binary number.
OUTPUT: The decimal number.
PROCESS:
Step 1: [Taking the input]
Read n [the binary number]
Step 2: [Converting from binary to decimal]
Set d<-0
Set p<-0
[Converting from binary to decimal]
While n>0 repeat
[Calculating the power of 2 and multiplied with the binary digit]
Set d<-d+(n mod 10)×2p
[Increasing the power]
Set p<-p+1
Set n<-n/10
[End of ‘while’ loop]
[Printing the decimal number]
Print "The decimal number is d”
Step 3: Stop.
while(n>0)-------------------------------------O(k)
{
//calculating the power of 2 and multiplied
//with the binary digit
d=d+(n%10)*pow(2,p);
//increasing the power
p+=1;
n=n/10;
}
The time complexity can be given as O(k) where ‘k’ is the number of digits of the binary numbers. The complexity can also be defined as O(log n) if n is the equivalent decimal number.
The space complexity is O(1) as the program requires a constant number of memory spaces to execute the program for any given input.