Given two binary strings, return their sum (also a binary string).
Example
a = 11
b = 1
Return 100
public class Solution {
public String addBinary(String a, String b) {
// 这是算法中很精妙的一步,如果 a 比 b 短,则让 a,b 互换
// 则可保证 a 永远为最长的字串
// 如此一来,这可以先通过循环处理完 b 后,再处理 a 剩下的部分
if(a.length() < b.length()){
String tmp = a; a = b; b = tmp;
}
int pa = a.length()-1;
int pb = b.length()-1;
int carries = 0; // // 每次的加法需要进位通过变量 carries 来传递
String rst = "";
while(pb >= 0){
int sum = (int)(a.charAt(pa) - '0') + (int)(b.charAt(pb) - '0') + carries;
// 当前位置的值等于 a b 相应位置的数及进位的数之和,取余
rst = String.valueOf(sum % 2) + rst;
carries = sum / 2;
pa --;
pb --;
}
while(pa >= 0){
int sum = (int)(a.charAt(pa) - '0') + carries;
rst = String.valueOf(sum % 2) + rst;
carries = sum / 2;
pa --;
}
if (carries == 1)
rst = "1" + rst;
return rst;
}
}