share my 2ms java solution beats 96%


  • 5
    C
    public String addBinary(String a, String b) {
    	char[] aArray = a.toCharArray();
    	char[] bArray = b.toCharArray();
        char[] sumArray = new char[Math.max(a.length(), b.length()) + 1];
        int index = sumArray.length - 1, carry = 0;
        for(int aIndex = a.length()-1, bIndex = b.length()-1; aIndex >=0 || bIndex >= 0; aIndex--, bIndex--){
            int aNum = aIndex < 0 ? 0 : aArray[aIndex] - '0';
            int bNum = bIndex < 0 ? 0 : bArray[bIndex] - '0';
            int sum = aNum + bNum + carry;
            sumArray[index--] = (char)('0' + (sum % 2));
            carry = sum / 2;
        }
        sumArray[0] = (char)('0' + carry);
        return carry == 0 ? new String(sumArray, 1, sumArray.length - 1): new String(sumArray);
    }

Log in to reply
 

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