
Sponsored
Sponsored
This approach uses bit manipulation to find the complement. The idea is to create a mask that has the same number of bits set to 1 as the number. By XORing the number with this mask, we effectively flip all the bits.
To create the mask, we can shift 1 left until it exceeds the number and then subtract 1 from it.
Time Complexity: O(1), the operations are done in constant time as the number of bits is fixed.
Space Complexity: O(1), no additional space is used.
1#include <iostream>
2
3using namespace std;
4
5int findComplement(int num) {
6 unsigned mask = ~0;
7 while (num & mask) mask <<= 1;
8 return ~mask & ~num;
9}
10
11int main() {
12 cout << findComplement(5) << endl; // Output: 2
13 cout << findComplement(1) << endl; // Output: 0
14 return 0;
15}The C++ solution uses a bitwise mask initialized to all bits 1. We left shift the mask until it has more bits than needed, then XOR with the negated mask.
This approach derives a mask by using the bit length of the number. We create a mask by taking 2n - 1, where n is the bit size of the number.
The result of the XOR between num and mask gives the complement.
Time Complexity: O(1)
Space Complexity: O(1)
1def
This Python function computes the mask based on the input's bit length, then returns the complement by XORing.