Straightforward java solution


  • 0
    F

    there is no math trick, but just be careful:

        public String addBinary(String a, String b) {
            int idx1 = a.indexOf('1');
            int idx2 = b.indexOf('1');
            if (idx1 < 0 && idx2 < 0) {
                return "0";
            }
            if (idx1 < 0) {
                return b.substring(idx2);
            }
            if (idx2 < 0) {
                return a.substring(idx1);
            }
            a = a.substring(idx1);
            b = b.substring(idx2);
            int len1 = a.length();
            int len2 = b.length();
            int diff = Math.abs(len1 - len2);
            char[] zeroes = new char[diff];
            Arrays.fill(zeroes, '0');
            String leadingZero = String.valueOf(zeroes);
            if (len1 < len2) {
                a = leadingZero + a;
            }
            if (len2 < len1) {
                b = leadingZero + b;
            }
            int carrier = 0;
            int max = Math.max(len1, len2);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = max - 1; i >= 0; i--) {
                int tmp = (a.charAt(i) - '0') + (b.charAt(i) - '0') + carrier;
                stringBuilder.append(tmp % 2);
                carrier = tmp / 2;
            }
            if (carrier != 0) {
                stringBuilder.append(carrier);
            }
            return stringBuilder.reverse().toString();
        }

Log in to reply
 

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