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 len = Math.max(a.length(),b.length());
char[] ch = new char[len + 1];//预防进位
int i = a.length() - 1;
int j = b.length() - 1;
//不考虑进位,所有相加
while(i >= 0 && j >= 0){
ch[len--] = (char) (a.charAt(i--) + b.charAt(j--) - '0');
}
//余下仅有一个还未加完
while(i >= 0){
ch[len--] = a.charAt(i--);
}
while(j >= 0){
ch[len--] = b.charAt(j--);
}
int k = 0;//进位
//处理进位
for(i = ch.length-1; i >=1; i--){
ch[i] = (char) (k + ch[i] - '0');
k = ch[i]/2;
ch[i] = (char) (ch[i]%2 + '0');
}
//推断是否还有进位
ch[0] = (char) (k > 0 ?
k +'0': '0'); //消除开头的0 return new String(ch).replaceAll("^0", ""); } }