Java straightforward solution


  • 0
    public class Solution {
        public int findComplement(int num) {
            int mask = Integer.MIN_VALUE; // 1000...
            // find first set bit
            while ((mask & num) == 0) {
                mask >>>= 1;
            }
            // flip the rest bits
            while (mask > 0) {
                num = num ^ mask;
                mask >>>= 1;
            }
            return num;
        }
    }

Log in to reply
 

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