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

Smallest power of 2 greater than or equal to n


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=n;
    int pos=-1;
    int count=0;
    while(n>0)
    {
        ++count;
        if((n&1)==1)
        pos=count;
        n=n>>1;
    }
    int num=1;
    num=num<<pos-1;
    if(num<k)
    num=num<<1;
    System.out.println(num);
}

}

0 Comments:

Post a Comment

Stats