Cleanest Java Solution (17 lines). Easy to understand. Vote me if you like it.


  • -1
    C
    public String addBinary(String a, String b) {
        String result="";
        int A,B,C,carry=0;
        a="0"+a; //In case top bit overflow. Use this trick to make code cleaner.
        b="0"+b;
        int aIndex=a.length()-1;
        int bIndex=b.length()-1;
        while(aIndex>=0||bIndex>=0){
            A=aIndex>=0?(a.charAt(aIndex)-'0'):0;
            B=bIndex>=0?(b.charAt(bIndex)-'0'):0;
            C=(A+B+carry)%2==0?0:1;
            carry=(A+B+carry)>=2?1:0;
            result=""+C+result;
            aIndex--;
            bIndex--;
        }
        if(result.charAt(0)=='0') return result.substring(1);
        else return result;
    }

Log in to reply
 

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