Accepted 2 ms Neat and Clean JAVA solution


  • 0
    M
    public String addBinary(String a, String b) {
            char[] a_chars = a.toCharArray();
            char[] b_chars = b.toCharArray();
            char carry = '0';
            
            int i = a_chars.length - 1;
            int j = b_chars.length - 1;
            
            while (i >= 0 && j >= 0) {
                if (a_chars[i] == '1' && b_chars[j] == '1') {
                    a_chars[i] = carry == '1' ? '1' : '0';
                    b_chars[j] = a_chars[i];
                    carry = '1';
                } else if (a_chars[i] == '1' || b_chars[j] == '1') {
                    a_chars[i] = carry == '1' ? '0' : '1';
                    b_chars[j] = a_chars[i];
                    carry = a_chars[i] == '1' ? '0' : '1';
                } else {
                    a_chars[i] = carry;
                    b_chars[j] = carry;
                    carry = '0';
                }
                i--;
                j--;
            }
            
            while (i >= 0 && carry == '1') {
                a_chars[i] = a_chars[i] == '1' ? '0' : '1';
                if (a_chars[i] == '1') carry = '0';
                i--;
            }
            
            while (j >= 0 && carry == '1') {
                b_chars[j] = b_chars[j] == '1' ? '0' : '1';
                if (b_chars[j] == '1') carry = '0';
                j--;
            }
            
            return (a_chars.length > b_chars.length) ? (carry == '1' ? carry + new String(a_chars) : new String(a_chars)) : (carry == '1' ? carry + new String(b_chars) : new String(b_chars));
        }
    

Log in to reply
 

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