4ms short java solution


  • 0
    F
    public String addBinary(String a, String b) {
        int i = a.length() - 1, j = b.length() - 1, carry = 0, sum = 0;
        String ret = "";
        while(i >= 0 || j >= 0){
            sum = carry;
            if(i>=0)    sum += (a.charAt(i--)-'0');
            if(j>=0)    sum += (b.charAt(j--)-'0');
            carry = sum / 2;
            ret = sum % 2 + ret;
        }
        return carry == 1 ? ("1" + ret) : ret;
    }

Log in to reply
 

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