My Java Solution


  • 0
    C

    public String addBinary(String a, String b) {
    if(a == null || a.isEmpty()) return b;
    if(b == null || b.isEmpty()) return a;
    int lenA = a.length();
    int lenB = b.length();

        int maxLen = lenA > lenB ? lenA:lenB;
    
        a = reverseString(a);
        b = reverseString(b);
    
        StringBuilder resultStr = new StringBuilder();
        Character[] elements = new Character[3];
        int counter = 0;
        elements[2] = '0';
        for (int i = 0; i < maxLen; i++) {
            if(i < lenA) elements[0] = a.charAt(i);
            else elements[0] = '0';
            if(i < lenB) elements[1] = b.charAt(i);
            else elements[1] = '0';
    
            counter = getCounterOfOne(elements);
            if(counter == 0) { resultStr.append('0'); elements[2] = '0'; }
            else if(counter == 1) { resultStr.append('1'); elements[2] = '0'; }
            else if(counter == 2) { resultStr.append('0'); elements[2] = '1'; }
            else { resultStr.append('1'); elements[2] = '1'; }
        }
    
        if(elements[2] == '1') resultStr.append('1');
        return resultStr.reverse().toString();
    
    }
    
    private Integer getCounterOfOne(Character[] elements) {
        int counter = 0;
        for (int i = 0; i < 3; i++)
            if(elements[i] == '1')  counter++;
        return counter;
    }
    
    private String reverseString(String str) {
        return new StringBuilder(str).reverse().toString();
    }

Log in to reply
 

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