LeetCode

Add Binary

Given two binary strings, return their sum (also a binary string).

For example,

a = "11"
b = "1"
Return "100".

Java

public class Solution {
    public String addBinary(String a, String b) {
        int aIndex = a.length() - 1;
        int bIndex = b.length() - 1;
        StringBuilder rst = new StringBuilder();
        int carry = 0;

        while(aIndex >= 0 || bIndex >= 0 || carry > 0) {
            int aValue = aIndex >= 0 ? a.charAt(aIndex--) - '0' : 0;
            int bValue = bIndex >= 0 ? b.charAt(bIndex--) - '0' : 0;
            int value = aValue + bValue + carry;
            carry = value / 2;
            rst.insert(0, value % 2);
        }
        return rst.toString();
    }
}