Write a program in java to take two binary numbers and print the summation of the two numbers
note if the second number is less in length than the first number then second no. will be pad up with zeros;
for ex: 1011+11 then its addition will be 1011+0011=1110
please it is very important i need it fast i have to show it tomorrow please please.....????
Answers
//package, include files
public String addTwoBinary(String s1, String s2) ;
public class binaryNumAdd {
String str1, str2, s; int i ;
public static void main (string[] args) {
Scanner input = new Scanner(System.in) ;
str1 = input.next() ; str2 = input.next();
i = str1.length() - str2.length();
if (i >0) while (i-- ) str2 = “0“ + str2 ; // pad with “0” in the front
else if (i< 0) while (i++ ) str1 = “0” + str1;
s = addTwoBinary(str1, str2);
System.out.println(s);
}
}
Public string addTwoBinary(String s1, String s2) { // strings of equal length
String s ; int i, sum=0, carry = 0;
for (i=s1.length -1 ; i >= 0; i--) {
sum = s1.charAt(i) - ‘0’ + s2.charAt(i) - ‘0’ + carry ;
carry = sum / 2; s = “” + (sum%2) + s ;
}
if (carry) s = “1” + s ;
return s ;
}