Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
一位一位的加就行了,考虑溢出。
public class Solution {
public String addBinary(String a, String b) {
int i = a.length()-1;
int j = b.length()-1;
int flow = 0;
StringBuilder strBuilder = new StringBuilder();
while(i >=0 && j >= 0){
if((a.charAt(i) == '0' || a.charAt(i) == '1')
&&(b.charAt(j) == '0' || b.charAt(j) == '1')){
int temp = a.charAt(i) - '0' + b.charAt(j) - '0' +flow;
flow = temp >=2 ? 1 :0;
temp = temp>=2 ?temp-2 : temp;
strBuilder.insert(0, temp);
}else{
return "";
}
i--;
j--;
}
while(i >= 0){
if(a.charAt(i) == '0' || a.charAt(i) == '1'){
int temp = a.charAt(i) -'0'+flow;
flow = temp >=2 ? 1 :0;
temp = temp>=2 ?temp-2 : temp;
strBuilder.insert(0, temp);
}else{
return "";
}
i--;
}
while(j >= 0 ){
if(b.charAt(j) == '0' || b.charAt(j) == '1'){
int temp = b.charAt(j) -'0'+flow;
flow = temp >=2 ? 1 :0;
temp = temp>=2 ?temp-2 : temp;
strBuilder.insert(0, temp);
}else{
return "";
}
j--;
}
if(flow == 1) strBuilder.insert(0, "1");
return strBuilder.toString();
}
}