Long but fast Java solution, 3ms.


  • 0
    M

    I judge and discuss each possible situation and deal with them. So the code is long. But the result is fine. 3ms, beating 87%.

    public class Solution {
        public String addBinary(String a, String b) {
            char[] achar = a.toCharArray();
            char[] bchar = b.toCharArray();
            int i = a.length()-1, j = b.length()-1, carry = 0;
            StringBuilder sb = new StringBuilder();
            for( ; i>=0 && j>=0; i--,j--){
                if (achar[i] != bchar[j])   sb.append(carry==0 ? '1' : '0');
                else if (achar[i]=='0' && bchar[j]=='0'){
                    sb.append(carry==0 ? '0' : '1');
                    carry = 0;
                } else if (achar[i]=='1' && bchar[j]=='1'){
                    sb.append(carry==0 ? '0' : '1');
                    carry = 1;
                }
            }
            while(i > j){
                for( ; i>=0 && carry == 0; i--)    sb.append(achar[i]);
                for( ; i>=0 && carry == 1; i--){
                    sb.append(achar[i] == '0' ? '1' : '0');
                    carry = (achar[i] == '0' ? 0 : 1);
                }
            }
            while(i < j){
                for( ; j>=0 && carry == 0; j--)    sb.append(bchar[j]);
                for( ; j>=0 && carry == 1; j--){
                    sb.append(bchar[j] == '0' ? '1' : '0');
                    carry = (bchar[j] == '0' ? 0 : 1);
                }
            }
            if(carry==1) sb.append('1');
            while(sb.length()>1 && sb.charAt(sb.length()-1)=='0')  sb.deleteCharAt(sb.length()-1);
            return sb.reverse().toString();
        }
    }
            
        }
    }
    

Log in to reply
 

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