Check whether K-th bit is set or not in java

0

 


This is on of the basic question of the data strcutres. In this you are given two numbers. First is number and a position and you have to find whether that position in that number's binary is set or not.


Example :

Input :

num = 5 ,  k =2

Output : false




public class Setbit {
public static boolean setbit(int n,int k)
{
if((n>>(k-1) & 1)==0)
return false;
return true;
}
public static int count(int n)
{
int count=0;
while(n>0)
{
if((n&1)==1)
{
count++;
}
n=n>>1;
}
return count;
}

public static void main(String args[])
{
int n=5,k=2;
System.out.println(setbit(n,k));
System.out.println(count(15));
System.out.println(count(22));
}
}


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !