Welcome to the exciting world of Bit Manipulation! This guide is designed to help you master common problems related to bit manipulation, an essential skill for any serious programmer. š”
Bit manipulation is a technique used to perform operations at the bit level, which can significantly improve the efficiency of algorithms, especially for tasks involving flags, masks, and shift operations.
Before diving into bit manipulation, let's understand how numbers are represented in binary.
Example: The binary number 1011 represents the decimal number 12^3 + 02^2 + 12^1 + 12^0 = 11.
&)The bitwise AND operation performs a logical AND on corresponding bits of two numbers.
Example:
1101 & 1010 = 1000
|)The bitwise OR operation performs a logical OR on corresponding bits of two numbers.
Example:
1101 | 1010 = 1111
^)The bitwise XOR operation performs a logical XOR on corresponding bits of two numbers.
Example:
1101 ^ 1010 = 0111
~)The bitwise NOT operation inverts all the bits of a number.
Example:
~1101 = 1010
<< and >>)The bitwise shift operations shift the bits of a number to the left or right.
<< : Shifts bits to the left.>> : Shifts bits to the right.Example:
1101 << 1 = 1110
1101 >> 1 = 0111
int num1 = 1101;
int num2 = 1010;
// Bitwise AND
int result1 = num1 & num2; // 1000
// Bitwise OR
int result2 = num1 | num2; // 1111
// Bitwise XOR
int result3 = num1 ^ num2; // 0111
// Bitwise NOT
int result4 = ~num1; // 1010
// Bitwise Shift Left
int result5 = num1 << 1; // 1110
// Bitwise Shift Right
int result6 = num1 >> 1; // 0111
Write a program to flip the bits of an integer.
Example:
Input: 1101
Output: 0010
Write a program to count the number of set bits (1s) in an integer.
Example:
Input: 1101
Output: 3
Write a program to check if a number is a power of two.
Example:
Input: 8
Output: True
Write a program to swap two numbers without using a temporary variable.
Example:
Input: num1 = 10, num2 = 20
Output: num1 = 20, num2 = 10
Write a program to find the position of the first set bit (first 1) in an integer.
Example:
Input: 1101
Output: 3
Write a program to toggle all set bits (1s) of an integer.
Example:
Input: 1101
Output: 0010
Write a program to find the position of the highest set bit (highest 1) in an integer.
Example:
Input: 1101
Output: 3
Write a program to find two numbers that differ by only one bit.
Example:
Input: 1101, 1010
Output: True
What does the bitwise AND operation do between two numbers?
What is the result of the following operation: 1101 & 1010?