Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Remember this time we need to read number from back instead of front
carry => num/2;
reminder => num%2
Be careful, reverse the StringBuilder as output String
public class Solution {
public String addBinary(String a, String b) {
if(a.length()==0) return b;
if(b.length()==0) return a;
StringBuilder strBuilder=new StringBuilder();
int al=a.length()-1;
int bl=b.length()-1;
int carry=0;
while(al>=0 && bl>=0){
//convert both Character to Integer
int numA=a.charAt(al)-'0';
int numB=b.charAt(bl)-'0';
int num=numA+numB+carry;
carry=num/2;
int reminder=num%2;
strBuilder.append(reminder);
al--;
bl--;
}
//check for case of a.length()>b.length();
while(al>=0){
int numA=a.charAt(al)-'0';
int num=numA+carry;
carry=num/2;
int reminder=num%2;
strBuilder.append(reminder);
al--;
}
//check for case of a.length()>b.length();
while(bl>=0){
int numB=b.charAt(bl)-'0';
int num=numB+carry;
carry=num/2;
int reminder=num%2;
strBuilder.append(reminder);
bl--;
}
//do not forget for last carry
if(carry>0){
strBuilder.append(carry);
}
//we need to reverse the String since we are read from left to right
return strBuilder.reverse().toString();
}
}