2ms, beats 97%, Neat Java solution


  • 0
    W

    public class Solution {

    public String addBinary(String a, String b) {
        return a.length() > b.length() ? addBinaryHelper(a, b) : addBinaryHelper(b, a);
    }
    
    public String addBinaryHelper(String l, String s) {
        int i = l.length() - 1, j = s.length() - 1, carry = 0, sum = 0;
        char[] c = l.toCharArray(), d = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        while (i >= 0) {
            if (j < 0) sum = c[i] - '0' + carry;
            else sum = c[i] - '0' + d[j--] - '0' + carry;
            carry = sum > 1 ? 1 : 0;
            sum %= 2;
            c[i--] = (char) (sum + '0');
        }
        return carry == 0 ? new String(c) : "1" + new String(c);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.