[leetcode]67.Add Binary
题目
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"
解法
思路
用两个指针分别指向a和b的末尾,将a和b最后一位分别转为数字,用carry来保存要进位的数字,初始为0。如果a和b相加结束后,carry为1,则在sb之后加一个1,最后将sb逆转就可得到最终的结果,当然,这里也是可以用栈来代替reverse()的。
代码
class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
while(i >= 0 || j >= 0) {
int sum = carry;
if(i >= 0) sum += a.charAt(i--) - '0';
if(j >= 0) sum += b.charAt(j--) - '0';
sb.append(sum % 2);
carry = sum / 2;
}
if(carry == 1) sb.append(carry);
return sb.reverse().toString();
}
}