Java bitwise operation solution


  • 0
    M
    public class Solution {
    public String addBinary(String a, String b) {
        StringBuffer result = new StringBuffer();
        if(a.length() < b.length()) {
            String tmp = a;
            a = b;
            b = tmp;
        }
        int len_a = a.length(), len_b = b.length();
        int last_a = len_a - 1, last_b = len_b - 1;
        int first = 0, second = 0, carry = 0, sum = 0;
        for(int i = 0; i < len_b; i++) {
            first = a.charAt(last_a - i) - '0';
            second = b.charAt(last_b - i)  - '0';
            sum = (first ^ second) ^ carry;
            carry = ((first ^ second) & carry) | (first & second);
            result.append(sum);
        }
        for(int i = len_b; i < len_a; i++) {
            first = a.charAt(last_a - i) - '0';
            sum = first ^ carry;
            carry = first & carry;
            result.append(sum);
        }
        if(carry == 1) {
            result.append(1);
        }
        return (result.reverse()).toString();
    }
    }

Log in to reply
 

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