10 Bitwise Interview Questions and Answers
Prepare for technical interviews with this guide on bitwise operations, featuring common questions and answers to enhance your understanding and skills.
Prepare for technical interviews with this guide on bitwise operations, featuring common questions and answers to enhance your understanding and skills.
Bitwise operations are fundamental to low-level programming and are essential for tasks that require direct manipulation of data at the binary level. These operations are crucial in fields such as embedded systems, cryptography, and performance optimization, where efficient data processing is paramount. Understanding bitwise operations can also provide deeper insights into how computers perform arithmetic and logic operations.
This article offers a curated selection of bitwise operation questions designed to test and enhance your understanding of this critical topic. By working through these questions, you will gain the confidence and knowledge needed to tackle bitwise-related challenges in technical interviews, thereby improving your problem-solving skills and technical acumen.
Bitwise operations are essential in low-level programming for manipulating individual bits of data. These operations include:
Example:
def bitwise_operations(a, b): and_result = a & b or_result = a | b xor_result = a ^ b not_a_result = ~a not_b_result = ~b return and_result, or_result, xor_result, not_a_result, not_b_result # Example usage a = 12 # 1100 in binary b = 10 # 1010 in binary results = bitwise_operations(a, b) print("AND:", results[0]) # 8 (1000 in binary) print("OR:", results[1]) # 14 (1110 in binary) print("XOR:", results[2]) # 6 (0110 in binary) print("NOT a:", results[3]) # -13 (inverts all bits of 12) print("NOT b:", results[4]) # -11 (inverts all bits of 10)
Bitwise shifting involves moving the bits of a binary number to the left or right. In Python, this is done using the <<
(left shift) and >>
(right shift) operators. Shifting bits to the left by n
positions multiplies the number by 2^n
, while shifting bits to the right by n
positions divides the number by 2^n
and discards the remainder.
def shift_bits(num, n): left_shift = num << n right_shift = num >> n return left_shift, right_shift # Example usage: left, right = shift_bits(8, 2) print(f"Left Shift: {left}, Right Shift: {right}") # Output: Left Shift: 32, Right Shift: 2
To generate a bit mask for isolating the k-th bit of an integer, use the left shift operator. By shifting the number 1 to the left by k positions, you create a bit mask where only the k-th bit is set to 1.
def generate_bit_mask(k): return 1 << k # Example usage: k = 3 mask = generate_bit_mask(k) print(bin(mask)) # Output: 0b1000
To count the number of set bits (1s) in an integer, use bitwise operations. Repeatedly check the least significant bit (LSB) and shift the integer to the right until all bits have been checked.
def count_set_bits(n): count = 0 while n: count += n & 1 n >>= 1 return count # Example usage print(count_set_bits(9)) # Output: 2 (binary representation of 9 is 1001) print(count_set_bits(15)) # Output: 4 (binary representation of 15 is 1111)
To swap two integers using XOR without a temporary variable, leverage the properties of the XOR operation. XORing a number with itself results in 0, and XORing a number with 0 results in the number itself.
def swap(a, b): a = a ^ b b = a ^ b a = a ^ b return a, b # Example usage x, y = 5, 10 x, y = swap(x, y) print(x, y) # Output: 10 5
To check if an integer is even or odd using bitwise operations, use the bitwise AND operator (&). The least significant bit (LSB) determines its parity: if the LSB is 0, the number is even; if the LSB is 1, the number is odd.
def is_even(n): return (n & 1) == 0 # Test cases print(is_even(4)) # True, 4 is even print(is_even(7)) # False, 7 is odd
To check if an integer is a power of two using bitwise operations, use the property that a power of two has exactly one bit set in its binary representation. Subtracting 1 from a power of two results in all bits after the single set bit becoming 1. Perform a bitwise AND operation between the number and the number minus one. If the result is zero, the number is a power of two.
def is_power_of_two(n): return n > 0 and (n & (n - 1)) == 0 # Examples print(is_power_of_two(4)) # True print(is_power_of_two(5)) # False
To find the single unique element in an array where every other element appears twice, use the XOR operation. XORing all the elements in the array will cancel out the numbers that appear twice, leaving only the unique element.
def find_unique_element(arr): unique_element = 0 for num in arr: unique_element ^= num return unique_element # Example usage: arr = [4, 1, 2, 1, 2] print(find_unique_element(arr)) # Output: 4
Gray code is a binary numeral system where two successive values differ in only one bit. This property is useful in error correction and minimizing errors in analog to digital conversions.
To convert a binary number to its Gray code equivalent:
To convert a Gray code back to its binary equivalent:
Example:
def binary_to_gray(n): return n ^ (n >> 1) def gray_to_binary(n): mask = n while mask != 0: mask >>= 1 n ^= mask return n # Example usage: binary_num = 10 # Binary: 1010 gray_code = binary_to_gray(binary_num) print(f"Gray code of {binary_num} is {gray_code}") gray_num = 15 # Gray code: 1111 binary_code = gray_to_binary(gray_num) print(f"Binary code of {gray_num} is {binary_code}")
To find the missing number in an array of n-1 integers in the range from 1 to n using bitwise operations, leverage the XOR operation. XORing all the numbers in the array with all the numbers from 1 to n will cancel out the duplicate numbers, leaving only the missing number.
def find_missing_number(arr, n): xor_all = 0 xor_arr = 0 for i in range(1, n + 1): xor_all ^= i for num in arr: xor_arr ^= num return xor_all ^ xor_arr # Example usage arr = [1, 2, 4, 5, 6] n = 6 print(find_missing_number(arr, n)) # Output: 3