试题:
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = “11”, b = “1”
Output: “100”
Example 2:
Input: a = “1010”, b = “1011”
Output: “10101”
代码:
按照加法规则从后往前加,注意进1,以及最后的carry。
class Solution {
public String addBinary(String a, String b) {
int one = a.length()-1;
int two = b.length()-1;
int carry = 0;
StringBuffer out = new StringBuffer();
while(one>=0 || two>=0){
int sum = carry;
sum += one>=0?a.charAt(one--)-'0':0;
sum += two>=0?b.charAt(two--)-'0':0;
out.insert(0, sum%2);
carry = sum/2;
}
if(carry>0){
out.insert(0,1);
}
return out.toString();
}
}