
Sponsored
Sponsored
This approach involves calculating a mask of the same bit length as the number and then using XOR to flip all the bits. The mask is calculated as a sequence of 1s of the same length as the binary representation of the number. For any number 'n', the mask would be computed as (1 << number_of_bits) - 1.
Time Complexity: O(log(n)) as we are shifting bits for the length of the number.
Space Complexity: O(1) since we are using a constant space.
1function bitwiseComplement(n) {
2 if (n === 0) return 1;
3 let mask = 0;
4 let m = n;
5 while (m !== 0) {
6 mask = (mask << 1) | 1;
7 m >>= 1;
8 }
9 return (~n) & mask;
10}
11
12console.log(bitwiseComplement(5));The JavaScript solution handles integer computations using bit manipulation techniques following the same strategy by determining a combined bitmask to calculate the bitwise complement.
In this approach, instead of calculating a mask using shifts, we use mathematical expressions. We calculate the highest power of 2 greater than n, subtract 1 to get a mask with all 1s up to the highest bit set in n. This mask is then XORed with n for the result.
Time Complexity: O(log(n)) for shifting mask while determining the next power of 2.
Space Complexity: O(1) as only simple variables are used.
1
This JavaScript solution makes use of bitshifts symbolized by '<<=', which is pivotal in both calculating the mask and deriving the effective binary complement of n.