Java solution, 6ms, O(n), simple, easy


  • 0
    R
    public String addBinary(String a, String b) {
        if(a.length()<b.length()){
            return addBinary(b,a);
        }
        int carryBit = 0;
        int diff = a.length()-b.length();
        StringBuffer appendZero = new StringBuffer();
        StringBuffer result = new StringBuffer();
        for(int index=0; index<diff; index++){
            appendZero.append("0");
        }
        appendZero.append(b);
        for(int index=a.length()-1; index>=0;index--){
            int aChar = a.charAt(index)-'0';
            int bChar = appendZero.charAt(index)-'0';
            StringBuffer temp = null;
            int current = (aChar+bChar+carryBit);
            if(current==3){
                carryBit=1;
                temp=new StringBuffer("1");
            }
            else if(current==2){
                carryBit=1;
                temp=new StringBuffer("0");
            }
            else{
                carryBit=0;
                if(current==1){
                    temp = new StringBuffer("1");
                }
                else{
                    temp = new StringBuffer("0");
                }
            }
            result = temp.append(result);
        }
        if(carryBit!=0){
            StringBuffer temp = new StringBuffer("1");
            result = temp.append(result);
        }
        return result.toString();
    }

Log in to reply
 

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