The Complement of Base 10 Integer interview question asks you to find the "bitwise complement" of a given integer N. The complement is formed by changing every 0 to a 1 and every 1 to a 0 in its binary representation. For example, 5 in binary is 101. Its complement is 010, which is 2 in base 10. Crucially, we only care about the bits up to the most significant bit of the original number.
Companies like Amazon and Google use this Bit Manipulation interview pattern to test a candidate's comfort level with binary operations. It requires understanding bitwise NOT (~), AND (&), and XOR (^). It also tests whether you can create a "mask" to isolate the specific bits you want to flip.
The most common approach is using an XOR Mask.
N.1s. For example, if N=5 (101), the mask is 7 (111).N XOR mask.
Alternatively, you can find the smallest power of 2 greater than N, subtract 1 to get the mask, and then perform the XOR.N = 10
1010.1111 (which is 15 in decimal).1010 ^ 1111 = 0101.0101 is 5 in decimal.
Result: 5.~N flips all bits in a 32-bit or 64-bit integer, including the sign bit, leading to a negative number instead of the expected complement.To quickly find a mask of all 1s for a number N, you can use the property that mask = (1 << number_of_bits) - 1. Just be careful with potential overflow if N is very large.