712531. Bit Manipulation
Bit Manipulation
Summary
This problem is about manipulating bits in a given number. You are asked to perform various operations on the bits, such as setting or clearing specific positions, checking if a bit is set at a certain position, and so on. This problem requires you to understand how binary numbers work and how to use bitwise operators to manipulate them.
Detailed Explanation
The key concept involved in this problem is bitwise manipulation. You will need to use the following bitwise operators:
&(bitwise AND)|(bitwise OR)^(bitwise XOR)~(bitwise NOT)
To solve this problem, you can start by defining a function that takes an integer as input and performs the desired operations on its bits. For example, if you want to set the bit at position i, you can use the following formula:
num |= 1 << i;
This shifts the binary number 1 to the left by i positions and then ORs it with the original number. This effectively sets the bit at position i.
To check if a bit is set at a certain position, you can use the following formula:
return (num & (1 << i)) != 0;
This shifts the binary number 1 to the left by i positions and then ANDs it with the original number. If the result is not zero, it means that the bit at position i is set.
Here's a step-by-step breakdown of the solution:
- Define a function
setBit(n, i)that takes an integernand an integerias input. - Use the formula above to set the bit at position
i. - Return the updated number.
Time complexity: O(1) Space complexity: O(1)
Optimized Solutions
Java
public class BitManipulation {
public static int setBit(int n, int i) {
return n | (1 << i);
}
}
Python
def set_bit(n, i):
return n | (1 << i)
C++
class BitManipulation {
public:
int setBit(int n, int i) {
return n | (1 << i);
}
};
JavaScript
function setBit(n, i) {
return n | (1 << i);
}
Not available