Leetcode

Number Complement

  • Time:O(32) = O(1)
  • Space:O(1)

C++

class Solution {
 public:
  int findComplement(long num) {
    for (long i = 1; i <= num; i <<= 1)
      num ^= i;
    return num;
  }
};

JAVA

class Solution {
  public int findComplement(int num) {
    for (long i = 1; i <= num; i <<= 1)
      num ^= i;
    return num;
  }
}