java solution


  • 0
    M
    public String addBinary(String a, String b) {
    	int lengthDiff = Math.abs(a.length() - b.length());		
        if (a.length() > b.length()){
            for (int j = 0; j < lengthDiff; j++){
                b = "0" + b;
            }
        }else if (b.length() > a.length()){
            for (int j = 0; j < lengthDiff; j++){
                a = "0" + a;
            }
        }
        String result = "";
        String remainder = "0";
        for(int i = a.length()-1; i >= 0; i--){
            String first = a.charAt(i) + "";
            String second = b.charAt(i) + "";
            result = getSumAndRemainder(first, second, remainder)[0] + result;
            remainder = getSumAndRemainder(first, second, remainder)[1];
        }
        if (remainder.equals("0"))
            return result;
        return remainder + result;
    }
    
    public String[] getSumAndRemainder(String a, String b, String c){
        if(a.equals("1") && b.equals("1") && c.equals("1")){
            return new String[]{"1","1"};
        }else if((a.equals("1") && b.equals("1")) || (b.equals("1") && c.equals("1")) || (a.equals("1") && c.equals("1"))){
            return new String[]{"0","1"};
        } else if(a.equals("1") || b.equals("1")  || c.equals("1")){
            return new String[]{"1","0"};
        }
        return new String[]{"0","0"};
    }

Log in to reply
 

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