Let's first understand the problem statement, and then we will understand the trick with a few examples.
Example:
Input: n = 13 Output: true Explanation: n = 13 = 1101 As the last bit is set bit so return true. Input: n = 8 Output: false Explanation: n = 8 = 1000 As the last bit is not set bit so return false.
Approach.
To check whether the last bit of a number is set, we perform a bitwise AND operation between the number and 1 (i.e., n & 1). This operation isolates the least significant bit. If the result is 1, the last bit is set; if it's 0, the last bit is not set. Let's understand the approach with a few examples:
Let's say n = 13.
So the binary representation of 13 is 1101.
As we want to perform an AND operation between n and 1, so binary representation of 1 is 0001.
1101 & 0001 = 0001 = 1, as the AND operation returns a set bit only if both bits are set.
We will get 1 in our result only if the last bit of the given number is a set bit, else it will always result in 0.
Example Code:
// Example C++: Check if last bit is Set bit
#include <iostream>
using namespace std;
void checkLastBit(int n) {
if (n & 1)
cout << "Last bit is set (1)" << endl;
else
cout << "Last bit is not set (0)" << endl;
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
checkLastBit(n);
return 0;
}
Enter a number: 13
Last bit is set (1)
This is one of the most commonly used micro-optimizations in competitive programming and interviews
No comments:
Post a Comment