My 2ms Java Solution, beat 95.63%, very easy to understand


  • 0
    C

    The solution is quite easy, use an array an array to store the final result. Then retrieve letters from each string each time, calculate the sum, mock the calculation of binary addition.
    '
    public String addBinary(String a, String b) {

        int aLen = a.length();
        int bLen = b.length();
        int maxLen = Math.max(aLen, bLen);
        int[] arrSum = new int[maxLen + 1];
             
         for (int i = 0; i < maxLen; i ++) {
            
            int numA = 0;
            int numB = 0;
            
            if (i < aLen)
                numA = a.charAt(aLen - 1 - i) - '0';
            if (i < bLen)
                numB = b.charAt(bLen - 1 - i) - '0';
                
            int curSum = numA + numB + arrSum[i];
            if ( curSum >= 2) {
                arrSum[i] = curSum % 2;
                arrSum[i + 1] = 1;
            }
            else {
                arrSum[i] = curSum;
            }
        }
        
        StringBuilder builder = new StringBuilder();
        
        for (int i = arrSum.length - 1; i >= 0; i --) {
            if (i == arrSum.length - 1 && 0 == arrSum[i])
                continue;
            builder.append(arrSum[i]);
        }
        
        return builder.toString();
    }
    

    '


Log in to reply
 

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