Add Two Binary Numbers in Java
Write a Java program to input two binary numbers from the user, and find and display their sum.
Following are the rules for adding binary digits:
0 + 0 = 0
0 + 1 = 1
1 + 0 = 1
1 + 1 = 0 with carry 1
1 + 1 + 1 = 1 with carry 1
Example:
INPUT:
1011
101
OUTPUT:
10000
import java.util.Scanner;
class BinaryAddition{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("First binary number: ");
String b1 = in.nextLine();
System.out.print("Second binary number: ");
String b2 = in.nextLine();
while(b1.length() < b2.length())
b1 = "0" + b1;
while(b2.length() < b1.length())
b2 = "0" + b2;
String sum = "";
char carry = '0';
for(int i = b1.length() - 1; i >= 0; i--){
char ch1 = b1.charAt(i);
char ch2 = b2.charAt(i);
if(ch1 == '0' && ch2 == '0'){
if(carry == '1'){
sum = "1" + sum;
carry = '0';
}
else
sum = "0" + sum;
}
else if(ch1 == '0' && ch2 == '1'){
if(carry == '1'){
sum = "0" + sum;
carry = '1';
}
else
sum = "1" + sum;
}
else if(ch1 == '1' && ch2 == '0'){
if(carry == '1'){
sum = "0" + sum;
carry = '1';
}
else
sum = "1" + sum;
}
else if(ch1 == '1' && ch2 == '1'){
if(carry == '1'){
sum = "1" + sum;
carry = '1';
}
else{
sum = "0" + sum;
carry = '1';
}
}
}
if(carry == '1')
sum = "1" + sum;
System.out.println("Sum = " + sum);
}
}
class BinaryAddition{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("First binary number: ");
String b1 = in.nextLine();
System.out.print("Second binary number: ");
String b2 = in.nextLine();
while(b1.length() < b2.length())
b1 = "0" + b1;
while(b2.length() < b1.length())
b2 = "0" + b2;
String sum = "";
char carry = '0';
for(int i = b1.length() - 1; i >= 0; i--){
char ch1 = b1.charAt(i);
char ch2 = b2.charAt(i);
if(ch1 == '0' && ch2 == '0'){
if(carry == '1'){
sum = "1" + sum;
carry = '0';
}
else
sum = "0" + sum;
}
else if(ch1 == '0' && ch2 == '1'){
if(carry == '1'){
sum = "0" + sum;
carry = '1';
}
else
sum = "1" + sum;
}
else if(ch1 == '1' && ch2 == '0'){
if(carry == '1'){
sum = "0" + sum;
carry = '1';
}
else
sum = "1" + sum;
}
else if(ch1 == '1' && ch2 == '1'){
if(carry == '1'){
sum = "1" + sum;
carry = '1';
}
else{
sum = "0" + sum;
carry = '1';
}
}
}
if(carry == '1')
sum = "1" + sum;
System.out.println("Sum = " + sum);
}
}
Comments
Post a Comment