Yet another java solution iterating through bits. Easy to understand.


  • 0
    C
    public class Solution {
        public int getSum(int a, int b) {
            int carry = 0;
            int result = 0;
            for (int i=0; i<32; i++) {
                int d1 = (a>>i)&1;
                int d2 = (b>>i)&1;
                //111, 110, 100, 000
                //d3:1, 0, 1, 0
                //carry: 1, 1, 0, 0
                int d3 = d1^d2^carry;
                if ( (d1&d2)==1||(d1&carry)==1||(d2&carry)==1 )
                    carry = 1;
                else carry = 0;
                result = result | d3<<i;
            }
            return result;
        }
    }
    

  • 0
    I

    are you allowed to use ++? Since we are not allowed to use +, and ++ is very similar to that, i thought interviewer would only accept hte half adder method


Log in to reply
 

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