share my fast JAVA solution


  • 0

    the following is fast

    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int carry = 0, p1 = a.length() - 1, p2 = b.length() - 1;
        while (p1 >= 0 && p2 >= 0) {
            carry += p1 >= 0 ? a.charAt(p1--) - '0' : 0;
            carry += p2 >= 0 ? b.charAt(p2--) - '0' : 0;
            sb.insert(0, (char) (carry % 2 + '0'));
            carry >>= 1;
        }
        while (p1 >= 0) {
            carry += p1 >= 0 ? a.charAt(p1--) - '0' : 0;
            sb.insert(0, (char) (carry % 2 + '0'));
            carry >>= 1;
        }
        while (p2 >= 0) {
            carry += p2 >= 0 ? b.charAt(p2--) - '0' : 0;
            sb.insert(0, (char) (carry % 2 + '0'));
            carry >>= 1;
        }
        if (carry == 1) {
            sb.insert(0, '1');
        }
        return sb.toString();
    }
    

    the following is clean

    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int carry = 0, p1 = a.length() - 1, p2 = b.length() - 1;
        while (p1 >= 0 || p2 >= 0 || carry == 1) {
            carry += p1 >= 0 ? a.charAt(p1--) - '0' : 0;
            carry += p2 >= 0 ? b.charAt(p2--) - '0' : 0;
            sb.insert(0, (char)(carry % 2 + '0'));
            carry >>= 1;
        }
        return sb.toString();
    }
    

Log in to reply
 

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