Question
Program to convert binary to decimal number using recursion
Enter the Binary number:111001
The decimal value of 111001 is 57
Enter the Binary number:-111001
The decimal value of 111001 is -57
Enter the Binary number:110002
Invalid Binary number
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.Scanner;
public class BinaryToDecimal
{
public static boolean isBinaryNumbervalid(long bin)
{
while(bin>0)
{
if(bin%10>1)
{
System.out.println("Invalid binary number");
return false;
}
bin=bin/10;
}
return true;
}
public static long BinaryToDecimalConversion(long bin,int power)
{
if(bin==0)
{
return 0;
}
else
{
return ((bin%10)*(long)Math.pow(2,power))+BinaryToDecimalConversion(bin/10,power+1);
}
}
public static void main()
{
long decimal=0,binary=0;
Scanner sc=new Scanner(System.in);
System.out.print("ENTER BINARY NUMBER:");
binary=sc.nextLong();
if(binary<0)//negative binary number
{
if(isBinaryNumbervalid(-binary)==true)
{
decimal=-BinaryToDecimalConversion(-binary,0);
/*
BinaryToDecimalConversion(-binary,0) will return positive decimal number
but we want negative decimal number so thats why
we added negative sign in front of BinaryToDecimalConversion(-binary,0)
*/
System.out.println("THE DECIMAL VALUE OF BINARY "+binary+" IS "+decimal);
}
}
else
{
if(isBinaryNumbervalid(binary)==true)
{
decimal=BinaryToDecimalConversion(binary,0);
System.out.println("THE DECIMAL VALUE OF BINARY "+binary+" IS "+decimal);
}
}
}
}
Python
def isBinaryNumberValid(binary):
if(binary==0):
return True
if(binary%10>1):
print("Invalid Binary number")
return False
else:
return isBinaryNumberValid(binary//10)
def binaryToDecimalConvertor(binary,power=0):
if(binary==0):
return 0
else:
remainder=binary%10
return remainder*(2**power)+binaryToDecimalConvertor(binary//10,power+1)
if(__name__=='__main__'):
decimalNumber=0
binaryNumber=int(input("Enter the Binary number:"))
if (binaryNumber < 0):
if (isBinaryNumberValid(-binaryNumber) == True):
decimalNumber = -binaryToDecimalConvertor(-binaryNumber)
# binaryToDecimalConvertor(-binaryNumber) will return positive decimal number
# but we want negative decimal number so thats why
# we added negative sign in front of binaryToDecimalConvertor(-binaryNumber)
print("The decimal value of", binaryNumber, "is", decimalNumber)
else:
if (isBinaryNumberValid(binaryNumber) == True):
decimalNumber = binaryToDecimalConvertor(binaryNumber)
print("The decimal value of", binaryNumber, "is", decimalNumber)