Simple 2ms java solution


  • 1
    Z
    public class Solution {
        public String addBinary(String a, String b) {
            int diff = Math.abs(a.length() - b.length());
            char[] charArray1 = a.length() >= b.length() ? a.toCharArray() : b.toCharArray();
            char[] charArray2 = a.length() >= b.length() ? b.toCharArray() : a.toCharArray();
            int maxLength = charArray1.length, carry = 0;
            for (int i = maxLength - 1; i >=0; i--) {
                int index2 = i - diff;
                char array1Element = charArray1[i];
                char array2Element = index2 >= 0 ? (char)(charArray2[index2] + carry) : (char)('0' + carry);
                if (array1Element == array2Element) {
                    charArray1[i] = '0';
                    carry = array1Element == '1' ? 1 : 0;
                } else if(array2Element == '0'|| array2Element == '1') {
                    charArray1[i] = '1';
                    carry = 0;
                }
            }
            String answer = carry == 1? carry + new String(charArray1) : new String(charArray1);
            return answer;
        }
    }

Log in to reply
 

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