my java solution 3ms


  • 0
    L
    public String addBinary(String a, String b) {
         int len1 = a.length(), len2 = b.length(),end1 = len1,end2 = len2;
         int maxLen = Math.max(len1,len2);
         int size = 0;
         int[] binarys = new int[maxLen + 1];
         while(size <= maxLen){
             if(size < len1) {
                 binarys[size] += a.charAt(--end1) - '0';
             }
             if(size < len2) {
                 binarys[size] += b.charAt(--end2) - '0';
             }
             if(binarys[size] >= 2){
                 binarys[size] %= 2;
                 binarys[size + 1] = 1;
             }
             size++;
         }
    
        StringBuffer buffer = new StringBuffer();
        if(binarys[maxLen] == 1){
            buffer.append(1);
        }
        for(int i = maxLen - 1; i >=0; i--){
            buffer.append(binarys[i]);
        }
    
        return buffer.toString();
    }

Log in to reply
 

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