Java Program

Object:-Write a program to Convert Binary number into decimal number

import java.util.Scanner; 

class BinaryToDecimal
{
   public static void main(String args[])
   {
     Scanner s=new Scanner(System.in);            
     System.out.println("Enter a binary number:");
     int n=s.nextInt();            
     int decimal=0,p=0;            
     while(n!=0)
     {
      decimal+=((n%10)*Math.pow(2,p));
      n=n/10;
      p++;
     }            
     System.out.println(decimal);
   }
}

Output

Enter a binary number:101
5
 

Explanation

For Example:
If the binary number is 111.
decimal = 1*(2^2) + 1*(2^1) + 1*(2^0) = 7








You may also like: