Java Program to Add two Binary numbers
In this program, I am demonstrated how to write a java program for two binary no addition in java.
package com;
import java.util.Scanner;
public class AddTwoBinaryNo
{
public static void main(String[] args)
{
long b1,b2;
int i=0,carry=0;
int [] sum = new int[10];
Scanner sc=new Scanner(System.in);
System.out.println("Enter your first binary no:");
b1=sc.nextLong();
System.out.println("Enter your second Binary No");
b2=sc.nextLong();
sc.close();
while(b1!=0||b2!=0)
{
sum[i++]=(int)((b1%10+b2%10+carry)%2);
carry=(int)((b1%10+b2%10+carry)/2);
b1=b1/10;
b2=b2/10;
}
if(carry!=0)
{
sum[i++]=carry;
}
--i;
System.out.print("Output: ");
while(i>=0)
{
System.out.println(sum[i--]);
}
System.out.print("\n");
}
}
Output:
Enter your first binary no:
11100
Enter your second Binary No
10101
Output:
110001
No comments:
Post a Comment