Complement of Base 10 Integer
Problem
The complement of an integer is the integer you get when you flip all the 0
’s to 1
’s and all the 1
’s to 0
’s in its binary representation.
- For example, The integer
5
is"101"
in binary and its complement is"010"
which is the integer2
.
Given an integer n
, return its complement.
Constraints
0 <= n <= 109
Solution
The problem Complement of Base 10 Integer
is the same as Number Complement.
Implementation
static const int fast_io = []()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution
{
public:
int bitwiseComplement(int n)
{
if (n == 0)
return 1;
unsigned int mask = n;
while (mask & (mask - 1))
mask &= mask - 1;
mask = (mask << 1) - 1;
return n ^ mask;
}
};