Clear and simple Java solution


  • 0
    F
    public String addBinary(String a, String b) {
        StringBuilder s = new StringBuilder();
        
        int posa = a.length() - 1;     // from least significant bit
        int posb = b.length() - 1;    // from least significant bit
        int carry = 0;   // store current partial sum
        while(posa >= 0 || posb >= 0 || carry > 0) {
            if (posa >= 0) {
                char c = a.charAt(posa);
                carry += c - '0';
                posa--;
            }
            if (posb >= 0) {
                char c = b.charAt(posb);
                carry += c - '0';
                posb--;
            }
            
            s.insert(0, (char) carry%2);
            carry = carry/2;    // update carry bit
        }
        
        return s.toString();
    }
    

Log in to reply
 

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