My two cents Java solution


  • 0
    C

    I think use string concatenation or StringBuilder method to insert at 0 position can be costly for large inputs. Another way around is to use StringBuilder's append() and then do reverse(). But I just used an array and scan from tail to front. Both should work fine.

    public class Solution {
       public String addBinary(String a, String b) {
        if(a == null || b == null) return "";
        
        // ensure length of a <= length of b
        if(a.length() > b.length())
            return addBinary(b,a);
        
        if(a.isEmpty()) return b;
        if(b.isEmpty()) return a;
        
        char[] sum = new char[b.length()];
        int c = 0;
        
        int diff = b.length() - a.length();
          
        for(int i = b.length() - 1; i >= 0; i--) {
            // index of a equals to (i - diff)
            char s = i - diff < 0 ? '0':a.charAt(i - diff);
            s = (char)(s + b.charAt(i) - '0' + c);
            
            // need carry?
            if(s > '1') {
                s = (char)(s - 2);
                c = 1;
            } else 
                c = 0;
                
            sum[i] = s; 
        }
        
        // the carry for the MSB
        if(c == 1) 
            return new StringBuilder().append('1').append(sum).toString();
        
        return new StringBuilder().append(sum).toString();
        }
    }

Log in to reply
 

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