Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
<span style="color:#333333;font-size: 14px; font-family: 'Times New Roman';">public class Solution {
public String addBinary(String a, String b) {
StringBuffer str = new StringBuffer();
int i = a.length() - 1;
int j = b.length() - 1;
int aa = 0;
int bb = 0;
int flag = 0;
while (i >= 0 || j >= 0){
aa = (i >= 0)? (a.charAt(i) - '0'):0;
bb = (j >= 0)? (b.charAt(j) - '0'):0;
str.append(aa^bb^flag); </span><span style="color:#ff6666;"><span style="font-family:Times New Roman;"><span style="font-size: 14px;">//这里用异或运算代替相加,得到的结果是一样的,如下 i</span><span style="font-size:12px;">nt tmp = (aa + bb + flag >= 2) ? (aa + bb + flag - 2): (aa + bb + flag);
<span style="white-space: pre;"> </span> str.append(tmp);</span></span></span><span style="color:#333333;font-size: 14px; font-family: 'Times New Roman';">
flag = (aa + bb + flag >= 2) ? 1 : 0;
i --;
j --;
}
if (flag == 1){
str.append("1");
}
str.reverse();
return str.toString();
}
}</span>