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) {// 1011int n = 11;int i = 2;if (isIthBitSet(n, i))System.out.println("Ith bit is set ");elseSystem.out.println("Not set");}// function to check the ith bit// if set return true else// return falseprivate static boolean isIthBitSet(int n, int 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 falsebool isIthBitSet(int n,int i){return n&(1<<(i-1));}int main(){//1011int n=11;int i=2;if(isIthBitSet(n,i))cout<<"Ith bit is set\n";elsecout<<"Not set\n";}
No comments:
Post a Comment