2ms java code


  • 0
    S
     public String addBinary(String a, String b) {
            int i=a.length()-1;
            int j=b.length()-1;
            int k=Math.max(i,j)+1;
            int carry='0';
            char[] result=new char[k+1];
            final int addFactor=1*'1'-1*'0';
            final  int zero1=0*'1'+3*'0';       
            final int one1=zero1+addFactor;      
            final int two1=one1+addFactor;
            final  int three1=two1+addFactor;
    
            while(i>=0||j>=0){
                int sum=
                     (i<0?'0':(a.charAt(i--)))
                   + (j<0?'0':(b.charAt(j--)))
                   + (carry);
                switch(sum){
                    case zero1:
                        result[k] = '0';
                        carry='0';
                        break;
                    case one1:
                        carry='0';
                        result[k] = '1';
                        break;        
                    case two1:
                        carry='1';
                        result[k] = '0';
                        break;
                    case three1:
                        carry='1';
                        result[k] = '1';
                        break;
                }
                k--;
            }
            if(carry=='1'){
                result[k]='1';
            }
            else{
                k++;
            }
            if(k==1){
               result[0]='0';
            }
            return new String(result,k,result.length-k);
        }

Log in to reply
 

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