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
ibecomes 0. i -= i & -i: This operation is key.i & -igives 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
xbeing assigned the value ofiin 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. Ifnumis5(101in binary),~numwill be...11111010in binary (in a 32-bit system, the leading bits are 1s becausenumis signed).(x - 1): This expression creates a bitmask. For example, if the highest set bit innumis the 3rd bit (like in5, which is101),xwill be100in binary, andx - 1will be011.- The
&operation withx - 1ensures that we only keep the relevant bits up to the highest bit set innumand 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), soibecomes4(100). - In the next iteration,
i = 4(100), andi & -i = 4(100), soibecomes0. - The loop exits with
x = 4(100). - Complement Calculation:
~numfor5(000...000101in binary) is111...111010.x - 1is3(011in binary).- The final result is
111...111010 & 000...000011, which equals010or2in decimal.
Therefore, the complement of 5 is 2.