Java Solution : Using "And" and "Or"


  • 0
    H
    public class Solution {
        public int getSum(int a, int b) {
             if (a == 0)
                return b;
            if (b == 0)
                return a;
            int up = 0, ret = 0;
            for (int i = 0; i < 32; i++) {
                int a1 = a & 0x01;
                int b1 = b & 0x01;
                if (a1 == 1) {
                    if (b1 == 1) {
                        if (up == 1) {
                            ret |= 1 << i;
                        }
                        up = 1;
                    } else {
                        if (up == 0) {
                            ret |= 1 << i;
                        }
                    }
                } else {
                    if (b1 == 1) {
                        if (up == 0) {
                            ret |= 1 << i;
                        }
                    } else {
                        if (up == 1) {
                            ret |= 1 << i;
                            up = 0;
                        }
                    }
                }
                a >>= 1;
                b >>= 1;
            }
            return ret;
    
        }
    }```

Log in to reply
 

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