
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#
In this C program, we calculate a mask such that all bits below the highest bit of num are 1. We then XOR num with this mask to get the complement.