Sharpen your knowledge of advanced bitwise operations, bit hacks, and practical binary manipulation techniques with these thoughtfully crafted questions. Improve your understanding of efficient algorithms and problem-solving strategies that leverage bitwise tricks.
Which bitwise operation can be used to determine if an integer is odd by examining its least significant bit?
Explanation: The expression 'num u0026 1' checks the least significant bit, which will be 1 if the number is odd and 0 if the number is even. The '| 2' operation would not directly test parity and may alter the number. '^ 0' leaves the number unchanged, serving no purpose in this context. 'u003Cu003C 1' shifts bits leftward, effectively multiplying by 2, and does not provide parity information.
Given an integer 'num' and a bit position 'k', which expression clears (sets to zero) the k-th bit using bitwise manipulation?
Explanation: To clear a specific bit, create a mask with '1 u003Cu003C k', invert it with the NOT operator '~', and AND it with the original number. '| (1 u003Cu003C k)' sets the bit rather than clearing it. '^ (1 u003Eu003E k)' and 'u0026 (1 u003Eu003E k)' reference a right shift, which is not appropriate for this operation and does not properly target the k-th bit.
Which bitwise trick is commonly used to count the number of 1-bits in an integer efficiently?
Explanation: Applying 'n = n u0026 (n - 1)' clears the lowest set bit each time and is a well-known trick for efficiently counting set bits in an integer. Multiplying by 2 and dividing by 2 shift the bit positions but do not directly count set bits. Toggling each bit with NOT does not help count the number of 1-bits in the original number.
How can you swap two integer variables 'a' and 'b' without using a temporary variable, utilizing bitwise operations?
Explanation: The XOR swap algorithm allows two integers to be swapped without a temporary variable using three XOR operations. The AND and OR variant given would not swap values and may lose information. The shift-based option moves bits but does not preserve the original values. The repeated use of OR and AND in the last option does not accomplish a correct swap.
What expression isolates the rightmost set bit (least significant 1) in a positive integer 'x'?
Explanation: The operation 'x u0026 -x' isolates the rightmost set bit efficiently by leveraging two's complement representation. The expression '| (x - 1)' turns on lower bits instead of isolating a single bit. The XOR with (x - 1) flips lower bits but does not isolate the rightmost one. Left-shifting moves bits to the left, not isolating any particular set bit.