Number Complement⚓︎
Description⚓︎
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 integer 2
.
Given an integer num
, return its complement.
Example 1:
- Input:
num = 5
- Output:
2
- Explanation:
The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
- Input:
num = 1
- Output:
0
- Explanation:
The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
Constraints:
1 <= num < 2^31
Solution⚓︎
Way 1⚓︎
- Time complexity: \(O(\log n)\);
- Space complexity: \(O(1)\).
Way 2⚓︎
See reference (Chinese).
Explanation:
Loop to Determine the Highest Bit Set in num
:
- This loop runs until
i
becomes 0. i -= i & -i
: This operation is key.i & -i
gives the lowest set bit ini
. By subtracting this fromi
, we essentially turn off the rightmost set bit in every iteration.- The loop continues until all bits are turned off, with
x
being assigned the value ofi
in each iteration. The final non-zero value ofi
(before becoming 0) is the highest set bit innum
.
Complement Calculation:
~num
: This operation flips all bits innum
. Ifnum
is5
(101
in binary),~num
will be...11111010
in binary (in a 32-bit system, the leading bits are 1s becausenum
is signed).(x - 1)
: This expression creates a bitmask. For example, if the highest set bit innum
is the 3rd bit (like in5
, which is101
),x
will be100
in binary, andx - 1
will be011
.- The
&
operation withx - 1
ensures that we only keep the relevant bits up to the highest bit set innum
and discard the leading 1s introduced by the~
operation.
Let's take an example to illustrate this:
Suppose num = 5
(101
in binary).
- Highest Bit Calculation:
- In the first iteration,
i = 5
(101
), andi & -i = 1
(001
), soi
becomes4
(100
). - In the next iteration,
i = 4
(100
), andi & -i = 4
(100
), soi
becomes0
. - The loop exits with
x = 4
(100
). - Complement Calculation:
~num
for5
(000...000101
in binary) is111...111010
.x - 1
is3
(011
in binary).- The final result is
111...111010 & 000...000011
, which equals010
or2
in decimal.
Therefore, the complement of 5
is 2
.