
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.
1function findComplement(num) {
2 let mask = ~0;
3 while (num & mask) mask <<= 1;
4 return ~mask & ~num;
5}
6
7console.log(findComplement(5)); // Output: 2
8console.log(findComplement(1)); // Output: 0;The JavaScript solution involves using a mask initialized to all 1s, left shifted, and then XORed with the negation of the input number.
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)
1#include <iostream>
2
using namespace std;
int findComplement(int num) {
unsigned mask = 1;
while (mask <= num) mask <<= 1;
return (mask - 1) ^ num;
}
int main() {
cout << findComplement(5) << endl; // Output: 2
cout << findComplement(1) << endl; // Output: 0
return 0;
}This C++ solution calculates a mask based on the bit-length and XORs it with the number to find the complement.