1009. Complement of Base 10 Integer( naive approach)
Documentation for Bitwise Complement Function
Intuition
The goal of the bitwiseComplement function is to compute the bitwise complement of a given non-negative integer n. The bitwise complement of a number is obtained by flipping all the bits in its binary representation. For example:
- The binary representation of
5is101. Its complement would be010, which is2. - The binary representation of
0is an edge case, and its complement is defined as1.
Approach
To achieve the bitwise complement, the function:
- Handles the special case where
nis0, returning1, since the binary representation is0and its complement is1. - Iteratively divides
nby2to retrieve its binary digits using modulus to find the remainder (rem). - For each bit, it computes its complement (using XOR with
1, i.e.,rem ^ 1) and accumulates the result intoansby converting the position of the bit back into decimal using powers of2. - Finally, it returns the accumulated result, which represents the bitwise complement of
n.
Step-by-Step Dry Run
Consider an example where n = 5.
Initialization
rem: To hold the current bitans: To accumulate the result (initialized to0)i: To keep track of the current bit position (initialized to0)
Handling Special Case
- Check if
n == 0:- If true, return
1. (In this casenis not0.)
- If true, return
While Loop Execution
Now, we enter the while loop since n is not 0.
The loop continues until n becomes 0.
First Iteration
- Current
n:5(binary101) - Calculate
rem:5 % 2 = 1(this is the least significant bit (LSB)) - Compute complement:
rem ^ 1 = 0 - Update
ans:ans = ans + (0) * pow(2, 0) = 0 - Update
n:n /= 2 => n = 2 - Increment
i:i = 1
Second Iteration
- Current
n:2(binary10) - Calculate
rem:2 % 2 = 0 - Compute complement:
rem ^ 1 = 1 - Update
ans:ans = 0 + (1) * pow(2, 1) = 2 - Update
n:n /= 2 => n = 1 - Increment
i:i = 2
Third Iteration
- Current
n:1(binary1) - Calculate
rem:1 % 2 = 1 - Compute complement:
rem ^ 1 = 0 - Update
ans:ans = 2 + (0) * pow(2, 2) = 2 - Update
n:n /= 2 => n = 0 - Increment
i:i = 3
Exit Loop
The loop exits as n is now 0.
Final Output
The function returns the value of ans, which is 2. This result is the bitwise complement of 5.
Additional Notes
- The use of
pow(2, i)can be replaced with bit shifting for better efficiency. - The overall time complexity is O(log n), as it processes each bit.
- The space complexity is O(1), using only a fixed amount of space for variables.
Code
class Solution {
public:
int bitwiseComplement(int n) {
int rem, ans=0,i=0;
if(n==0)
return 1;
while(n){
rem = n % 2;
ans = ans + (rem ^ 1) * pow(2, i);
i++;
n /= 2;
}
return ans;
}
};
This documentation can serve as a reference for understanding how the bitwiseComplement function operates, enabling you to recall its functionality and logic in the future.