1009. Complement of Base 10 Integer (Best approach)
Let's break down the bitwiseComplement function in the provided C++ code step by step, explaining the intuition, approach, and a dry run for clarity.
Intuition
The bitwise complement of a number is obtained by flipping its bits: changing every 0 to 1 and every 1 to 0. For example:
- The bitwise complement of
5(which is101in binary) is2(which is010in binary). - The bitwise complement of
0is defined as1in this function.
Approach
- Handle the Special Case: If
nis0, return1immediately since the complement of0is1. - Initialize Variables: Use
ansto store the result (the complement) andbitPositionto track the current bit position. - Iterate Over Bits: Use a loop to process each bit of
nuntilnbecomes0.- For each bit:
- Compute the complement of the least significant bit (LSB) using the expression
((n & 1) ^ 1). - Shift this complemented bit to its correct position using
<< bitPosition. - Use the bitwise OR (
|=) to add this bit into the resultans.
- Compute the complement of the least significant bit (LSB) using the expression
- Right shift
nto process the next bit and incrementbitPosition.
- For each bit:
- Return Result: Once all bits are processed, return
ans.
Step-by-Step Dry Run
Let’s dry run the function with an example. Consider n = 5.
Binary Representation
5in binary is101.
Step-by-Step Execution
-
Initial State:
n = 5(binary:101)ans = 0(binary:0)bitPosition = 0
-
First Iteration:
- Check
n > 0: True - Compute complement of LSB:
((n & 1) ^ 1)n & 1gives1(LSB of101),1 ^ 1gives0.
- Shift left:
0 << 0gives0. - Update
ans:ans |= 0→ans = 0. - Right shift
n:n >>= 1→n = 2(binary:10). - Increment
bitPosition:bitPosition = 1.
- Check
-
Second Iteration:
- Check
n > 0: True - Compute complement of LSB:
((n & 1) ^ 1)n & 1gives0(LSB of10),0 ^ 1gives1.
- Shift left:
1 << 1gives2(binary:10). - Update
ans:ans |= 2→ans = 2(binary:10). - Right shift
n:n >>= 1→n = 1(binary:1). - Increment
bitPosition:bitPosition = 2.
- Check
-
Third Iteration:
- Check
n > 0: True - Compute complement of LSB:
((n & 1) ^ 1)n & 1gives1(LSB of1),1 ^ 1gives0.
- Shift left:
0 << 2gives0. - Update
ans:ans |= 0→ans = 2. - Right shift
n:n >>= 1→n = 0. - Increment
bitPosition:bitPosition = 3.
- Check
-
Exit Loop:
- Check
n > 0: False (exit loop).
- Check
-
Return Result:
- Return
ans, which is2.
- Return
Conclusion
The function effectively computes the bitwise complement of a given integer by iterating through each bit, flipping it, and reconstructing the result bit by bit. The approach is efficient and straightforward, leveraging bitwise operations for clarity and performance.