[LC] 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"

class Solution {
    public String addBinary(String a, String b) {
        int aIndex = a.length() - 1;
        int bIndex = b.length() - 1;
        int carry = 0;
        StringBuilder sb = new StringBuilder();
        while (aIndex >= 0 || bIndex >= 0) {
            int curIndex = carry;
            if (aIndex >= 0) {
                curIndex += a.charAt(aIndex) - '0';            
            }
            if (bIndex >= 0) {
                curIndex += b.charAt(bIndex) - '0';            
            }            
            sb.append(curIndex % 2);
            carry = curIndex / 2;
            aIndex -= 1;
            bIndex -= 1;
        }
        if (carry == 1) {
            sb.append(1);
        }
        return sb.reverse().toString();
    }
}

猜你喜欢

转载自www.cnblogs.com/xuanlu/p/12591185.html