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"

Solution

模拟加法
注意点:
1. 计算要从个位开始,弄清楚下标如何计算
2. 注意最后的进位是否为1

Complexity

O(n) O(n)

Code

class Solution {
    public String addBinary(String a, String b) {
        int minLength = Math.min(a.length(), b.length());
        StringBuilder sb = new StringBuilder();
        int carry = 0;
        for(int i = 0; i < minLength; i++){
            int sum = a.charAt(a.length() - i - 1) - '0' + b.charAt(b.length()-i-1) - '0' + carry;
            carry = sum / 2;
            sb.append(sum % 2);
        }
        if(a.length() > b.length()){
            int i = a.length() - b.length() - 1;
            while(i >= 0){
                int sum = a.charAt(i) - '0' + carry;
                carry = sum / 2;
                sb.append(sum % 2);
                i--;
            }
        }else if(a.length() < b.length()){
            int i = b.length() - a.length() - 1;
            while(i >= 0){
                int sum = b.charAt(i) - '0' + carry;
                carry = sum / 2;
                sb.append(sum % 2);
                i--;
            }
        }
        if(carry != 0){
            sb.append(carry);
        }
        return sb.reverse().toString();
    }
}