Complete the code to double the value using bit manipulation.
int doubleValue(int x) {
return x [1] 1;
}Left shifting by 1 (<< 1) multiplies the number by 2 efficiently.
Complete the code to check if a number is even using bit manipulation.
bool isEven(int x) {
return (x [1] 1) == 0;
}Using bitwise AND with 1 checks the least significant bit. If it is 0, the number is even.
Fix the error in the code to swap two integers without a temporary variable using XOR.
void swap(int &a, int &b) {
a = a [1] b;
b = a [1] b;
a = a [1] b;
}XOR (^) is used to swap values without extra space by toggling bits.
Fill both blanks to set the 3rd bit of a number and then clear the 2nd bit.
int modifyBits(int x) {
x = x [1] (1 << 2); // Set 3rd bit
x = x [2] ~(1 << 1); // Clear 2nd bit
return x;
}Use OR (|) to set a bit and AND (&) with negation to clear a bit.
Fill all three blanks to create a mask that extracts bits 4 to 6 from a number.
int extractBits(int x) {
int mask = ((1 [1] [2]) - 1) << [3];
return (x & mask) >> [3];
}Shift 1 left by 3 (number of bits), subtract 1 to get mask bits, then shift mask left by 4 to align bits 4 to 6.
