Check Whether the Last Bit is a Set Bit or Not.

While solving Bit Manipulation, we sometimes use several tricks, and one such trick that we are going to discuss here is how to check if the last bit of any given number is set or not. It is an easy one-line trick, but used to solve many Bit Manipulation-related problems. One such popular example is finding if a number is even or odd using Bit Manipulation. 

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;
}
Output:

Enter a number: 13

Last bit is set (1)


This is one of the most commonly used micro-optimizations in competitive programming and interviews

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS