0067. Add Binary

https://leetcode.com/problems/add-binary

Description

Given two binary strings a and b, return their sum as a binary string.

Example 1:

**Input:** a = "11", b = "1"
**Output:** "100"

Example 2:

**Input:** a = "1010", b = "1011"
**Output:** "10101"

Constraints:

  • 1 <= a.length, b.length <= 104

  • a and b consist only of '0' or '1' characters.

  • Each string does not contain leading zeros except for the zero itself.

ac

StringBuilder reverse()

class Solution {
    public String addBinary(String a, String b) {
        // edge cases
        if (a == null || b == null || a.length() == 0 && b.length() == 0) return "";

        // add
        StringBuilder sb = new StringBuilder();
        int carry = 0;
        int ia = a.length() - 1, ib = b.length() - 1;
        while (ia >= 0 || ib >= 0 || carry != 0) {
            int curr = 0;
            curr += ia >= 0 ? a.charAt(ia--) - '0' : 0;
            curr += ib >= 0 ? b.charAt(ib--) - '0' : 0;
            curr += carry;
            sb.append("" + (curr % 2));
            carry = curr / 2;
        }

        return sb.reverse().toString();
    }
}

Last updated