Easy
- 用char[] 比s.charAt()快
- 二进制加的时候,可能暂时加出来3,这时候要进位后剩下的是3 % 2而不是0;不可能加出来4或者更大了,进位也最多只能进1.
class Solution {
public String addBinary(String a, String b) {
char[] aChars = a.toCharArray();
char[] bChars = b.toCharArray();
int i = aChars.length - 1;
int j = bChars.length - 1;
int carry = 0;
StringBuilder sb = new StringBuilder();
while (i >= 0 || j >= 0){
int sum = carry;
carry = 0;
if (i >= 0){
sum += aChars[i] - '0';
i--;
}
if (j >= 0){
sum += bChars[j] - '0';
j--;
}
if (sum >= 2){
carry += 1;
sum %= 2;
}
sb.append(sum);
}
if (carry != 0){
sb.append(carry);
}
return sb.reverse().toString();
}
}