Check if ith bit is set

To check the ith bit set or not we left shift the 1 by i-1 position and then  & with n.

Formula: n&(1<<(i-1)) 

Example 1:

Input : n=11 , i=2
Output: Ith bit is set

Example 2:

Input : n=10 , i=3
Output: Not set

Approach:

Java

public class CheckithbitisSet {
    public static void main(String[] args) {
        // 1011
        int n = 11;
        int i = 2;
        if (isIthBitSet(n, i))
            System.out.println("Ith bit is set ");
        else
            System.out.println("Not set");
    }

    // function to check the ith bit
    // if set return true else
    // return false
    private static boolean isIthBitSet(int nint i) {
        int r = n & (1 << (i - 1));
        if (r > 0)
            return true;
        return false;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

//function to check the ith bit
// if set return true else
//return false
bool isIthBitSet(int n,int i)
{
    return n&(1<<(i-1));
}
int main()
{
    //1011
    int n=11;
    int i=2;
    if(isIthBitSet(n,i))
       cout<<"Ith bit is set\n";
    else
     cout<<"Not set\n";
}



No comments:

Post a Comment