package miscellaneous.math.arithmetic.add.lc067_addbinary;

/**
 * Given two binary strings, return their sum (also a binary string).
 * For example, a = "11", b = "1". Return "100".
 */
public class Solution {

    public String addBinary(String a, String b) {
        if (a.length() == 0 || b.length() == 0) {
            return "0";
        }

        StringBuilder ret = new StringBuilder();
        int carry = 0;
        for (int i = a.length()-1, j = b.length()-1; (i >= 0 || j >= 0); i--, j--) {
            int d1 = (i < 0) ? 0 : (a.charAt(i) - '0');
            int d2 = (j < 0) ? 0 : (b.charAt(j) - '0');
            int sum = d1 + d2 + carry;
            if (sum >= 2) {
                ret.insert(0, sum % 2);
                carry = 1;
            } else {
                ret.insert(0, sum);
                carry = 0;
            }
        }

        if (carry == 1) {
            ret.insert(0, carry);
        }
        return ret.toString();
    }

}

@@ -213,31 +213,669 @@
     
-public String addBinary
+// My 2AC: emulate elegant template code%0A    public String addBinary(String a, String b) %7B%0A        StringBuilder result = new StringBuilder();%0A        int i = a.length() - 1, j = b.length() - 1;%0A        int carry = 0;%0A        while (i %3E= 0 %7C%7C j %3E= 0 %7C%7C carry != 0) %7B%0A            int b1 = (i %3E= 0) ? Character.getNumericValue(a.charAt(i--)) : 0;%0A            int b2 = (j %3E= 0) ? Character.getNumericValue(b.charAt(j--)) : 0;%0A            int sum = b1 + b2 + carry;%0A            carry = sum / 2;%0A            result.insert(0, sum %25 2);%0A        %7D%0A        return result.length() == 0 ? %220%22 : result.toString();%0A    %7D%0A%0A    // My 1AC: not bad%0A    public String addBinary1
 (Str

leetcode-067 add binary