Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Saturday, September 30, 2017

Off Kth Bit


Idea is to use & with all 1's except kth position (kth pos - 0)

 -> (~(1<<(c-k)))

Code:

public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
    int n=ab.nextInt();
    int k=ab.nextInt();
    int ans;
    if(k<=0)
    ans=n;
    else
    {
        int cur=n;
        int c=0;
        while(cur>0)
        {
            ++c;
            cur=cur>>1;
        }
        ans=n&(~(1<<(c-k)));
    }
    System.out.println(ans);
}

0 Comments:

Post a Comment

Stats