Very long but quick java solution, 3ms, beats 91.4%


  • 0
    L

    public static String addBinary(String a, String b) {

        char[] aa=a.toCharArray();
        char[] bb=b.toCharArray();
        int alen=a.length();
        int blen=b.length();
        int clen=Math.max(alen,blen)+1;
        char[] cc=new char[clen];
        int mark=0;
        int len=Math.min(alen,blen);
        while(len>0){
            if(mark==0){
                if(aa[alen-1]=='1'&&bb[blen-1]=='1'){
                    cc[clen-1]='0';
                    mark=1;
                }else if(aa[alen-1]=='0'&&bb[blen-1]=='0'){
                    cc[clen-1]='0';
                    mark=0;
                }else{
                    cc[clen-1]='1';
                    mark=0;
                }
            }else{
                if(aa[alen-1]=='1'&&bb[blen-1]=='1'){
                    cc[clen-1]='1';
                    mark=1;
                }else if(aa[alen-1]=='0'&&bb[blen-1]=='0'){
                    cc[clen-1]='1';
                    mark=0;
                }else{
                    cc[clen-1]='0';
                    mark=1;
                }
            }
            alen--;blen--;clen--;len--;
        }
        while(clen>0){
            if(alen>0){
                if(mark==0){
                    if(aa[alen-1]=='1'){
                        cc[clen-1]='1';
                    }else{
                        cc[clen-1]='0';
                    }
                }else{
                    if(aa[alen-1]=='1'){
                        cc[clen-1]='0';
                    }else{
                        cc[clen-1]='1';
                        mark=0;
                    }
                }
                
            }if(blen>0){
                if(mark==0){
                    if(bb[blen-1]=='1'){
                        cc[clen-1]='1';
                    }else{
                        cc[clen-1]='0';
                    }
                }else{
                    if(bb[blen-1]=='1'){
                        cc[clen-1]='0';
                    }else{
                        cc[clen-1]='1';
                        mark=0;
                    }
                }
               
            }
            if(alen<=0&&blen<=0&&clen>0){
                if(mark==1){
                    cc[clen-1]='1';
                    mark=0;
                }else
                cc[clen-1]='0';
            }
            clen--;alen--; blen--;
        }
        String result = new String(cc);
        if(cc[0]=='0')
        result=result.substring(1);
        
        return result;
    }

Log in to reply
 

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