Use Stack for easier understanding. Java.


  • 0
    N
    public class Solution {
        public int findComplement(int num) {
            Stack<Integer> stack = new Stack<Integer>();
            while (num > 0) {
                stack.push((num & 1) ^ 1);
                num = num >> 1;
            }
            int res = 0;
            while (!stack.isEmpty()) {
                res = res * 2 + stack.pop();
            }
            return res;
        }
    }

Log in to reply
 

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