4ms Java Solution


  • 0
    A
    public class Solution {
        public String addBinary(String a, String b) {
            if (a.length() < b.length()) return addBinary(b, a);
            StringBuilder c = new StringBuilder();
            int a_len = a.length(), b_len = b.length();
            char carry = '0';
            for (int i = 0; i <= b_len - 1; i++) {
                char[] sum_carry1 = add(a.charAt(a_len - 1 - i), b.charAt(b_len - 1 - i));
                char[] sum_carry2 = add(sum_carry1[0], carry);
                carry = add(sum_carry1[1], sum_carry2[1])[0];
                c.append(sum_carry2[0]);
            }
            for (int i = 0; i <= (a_len - b_len) - 1; i++) {
                char[] sum_carry = add(a.charAt(a_len - 1 - b_len - i), carry);
                carry = sum_carry[1];
                c.append(sum_carry[0]);
            }
            if (carry == '1') {
                c.append('1');
            }
            return reverse(c.toString());
        }
        
        String reverse(String s) {
            StringBuilder sb = new StringBuilder();
            for (int i = s.length() -1 ; i >= 0; i--) {
                sb.append(s.charAt(i));
            }
            return sb.toString();
        }
        
        public char[] add(char a, char b) {
            char[] sum_carry = new char[2];
            if (a != b) {
                sum_carry[0] = '1';
                sum_carry[1] = '0';
                return sum_carry;
            }
            sum_carry[0] = '0';
            if (a == '0') {
                sum_carry[1] = '0';
            } else {
                sum_carry[1] = '1';
            }
            return sum_carry;
        }
    }

Log in to reply
 

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