Very concise Recursive Java Solution


  • 0
    private String addBinaryRec(String a, String b, int aIdx, int bIdx, int carry) {
        if(aIdx<0 && bIdx<0 && carry==0)
            return "";
        
        int aVal = aIdx>=0 ? Integer.parseInt(""+a.charAt(aIdx)) : 0;
        int bVal = bIdx>=0 ? Integer.parseInt(""+b.charAt(bIdx)) : 0;
        
        int sum = aVal+bVal+carry;
        int val = sum % 2;
        int newCarry = sum / 2;
        
        return addBinaryRec(a,b,aIdx-1,bIdx-1,newCarry)+val;
    }
    
    public String addBinary(String a, String b) {
        if(a==null || a.isEmpty() || b==null || b.isEmpty())
            return "";
        return addBinaryRec(a,b,a.length()-1,b.length()-1,0);
    }

Log in to reply
 

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