Concise Java Solution 2ms Beats 97%


  • 0
    public String addBinary(String a, String b) {
        String sum_str = "";
        int curr_sum = 0;
        int offset = 0;
        int advance = 0;
        char[] a_chs = a.toCharArray();
        char[] b_chs = b.toCharArray();
        char[] longer = a_chs.length > b_chs.length ? a_chs : b_chs;
        char[] shorter= a_chs.length > b_chs.length ? b_chs : a_chs;
      
        if( a_chs.length==0 || b_chs.length==0 )  //ilegal input
            return a_chs.length > b_chs.length ? a : b;
        
        for ( ; offset < shorter.length; offset++){
            curr_sum = (longer[longer.length-1-offset]-'0') + (shorter[shorter.length-1-offset]-'0')+advance;
            longer[longer.length-1-offset] = (char)(curr_sum%2 + '0');
            advance = curr_sum/2;
        }
        
        while(advance==1 && offset < longer.length){
            curr_sum = longer[longer.length-1-offset]-'0'+advance; 
            longer[longer.length-1-offset] = (char)(curr_sum%2+'0');
            advance = curr_sum/2;
            offset++;
        }
        sum_str = String.valueOf(longer);
        if( advance==1 ) sum_str = '1' + sum_str;
        
        return sum_str;
    }

Log in to reply
 

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