Saturday, January 21, 2017

Addition of Two Binary Numbers

Tags

Following program accepts two binary numbers and gives the sum of that two binary numbers

/import java.util.*;
public class Table
{
    public static void main(String[] nt)
    {   int[] sum=new int [20];
        Scanner in=new Scanner(System.in);
        System.out.println("Enter Two Binary Numbers");
        long binary1=in.nextLong();
        long binary2=in.nextLong();
        int i=0,carry=0;
        while(binary1!=0||binary2!=0)
        {sum[i++]=(int)((binary1%10+binary2%10+carry)%2);
         carry=(int)((binary1%10+binary2%10+carry)/2);
         binary1=binary1/10;
         binary2=binary2/10;
        }
        if(carry!=0)
        {
            sum[i]=carry;
        }
        System.out.print("Sum is: ");
        while(i>=0)
        {
            System.out.print(sum[i--]);
        }
        System.out.println();
       
    }
   
}

Output: