Check whether kth bit is set or not

Input: n = 5, k = 1

Output: SET


Input: n = 6, k = 2

Ouput: NOT SET


Explanation:

To get kth bit left shift 1 by k-1, do AND operation with n to get the kth bit.

We have k-1 because, the bit positions are like, 1,2,3,4.... To get the first bit we have to shift by zero, to get second bet we have to shift 1 by one....Hence k-1.

If k has values starting from 0 then we can shift by k instead of k-1.


Code:

import java.util.*;

public class Solution {

    public static void main(String[] args){
     
        int n = 5, k=3;
     
        if( ( n & ( 1 << ( k-1) ) ) != 0)
            System.out.print("SET");
        else
            System.out.print("NOT SET");
     
        }
}


Output:
SET


Examples:
5 -> 101

k=1:
    left shift 1 by k-1 -> left shift by 0 -> 001
    101 & 001 not zero
k=2:
   left shift 1 by k-1 -> left shift by 1 -> 010
   101 & 010 is zero, Hence not set 






Comments

Popular posts from this blog

Rearrange Array in Maximum-Minimum form

Second Largest Element

Check if a number is a power of another number