criskgl
11/4/2019 - 4:57 PM

Add Binary

public String addBinary(String a, String b) {
    /*CASES
    A B S C    R = S + C
    0 0 0 0    0 
    0 1 1 0    1
    1 0 1 0    1
    1 1 0 1    1
    */
    int A = Integer.parseInt(a, 2);
    int B = Integer.parseInt(b, 2);
    
    int sum = A ^ B;
    
    int carry = (A & B) << 1;
    
    int result = sum ^ carry;//sum + carry
    
    int resultCarry = (sum & carry) << 1;
    
    //Until our resultCarry is 0 we wont stop adding it.
    //Note that this loop could never need to be executed if resultCarry is at the very beg 0
    while(resultCarry != 0){
        int lastCarry = resultCarry;
        int lastResult = result;
        result = (lastCarry ^ lastResult);
        resultCarry = (lastCarry & lastResult) << 1;
    }
    return Integer.toString(result, 2);
}