Number Complement

easy bit manipulation

Problem

The complement of a positive integer is the number you get by flipping all the bits of its binary representation. Given num, return its complement.

Inputnum = 5
Output2
5 = 101 → flipped 010 = 2. The leading zero bits do not count.

def find_complement(num):
    mask = 1
    while mask <= num:
        mask <<= 1
    return (mask - 1) ^ num
function findComplement(num) {
  let mask = 1;
  while (mask <= num) mask <<= 1;
  return (mask - 1) ^ num;
}
class Solution {
    public int findComplement(int num) {
        long mask = 1;
        while (mask <= num) mask <<= 1;
        return (int) ((mask - 1) ^ num);
    }
}
int findComplement(int num) {
    long mask = 1;
    while (mask <= num) mask <<= 1;
    return (int)((mask - 1) ^ num);
}
Time: O(log num) Space: O(1)