Sunday, July 8, 2007

Write C code to check if an integer is a power of 2 or not in a single line?

Even this is one of the most frequently asked interview questions. I really dont know whats so great in it. Nevertheless, here is a C program

Method1


if(!(num & (num - 1)) && num)
{
// Power of 2!
}


Method2


if(((~i+1)&i)==i)
{
//Power of 2!
}


I leave it up to you to find out how these statements work.

5 comments:

  1. we can do it as

    int findpower(unsigned char x)
    {
    return !((x-1)&x)
    }

    if its true then its power of 2 else its not....

    ReplyDelete
  2. if((double)((int)(log(n)*1.0/log(2))) == (log(n)*1.0/log(2)))
    {
    // power of 2
    }

    ReplyDelete
  3. above should be good for any power-of number, not just 2

    ReplyDelete
  4. I give u best solution.
    Logic- when u convert a decimal number to its binary number then u get series of 1 and 0
    Now if a number is power of two then u will observe it has only one (bit 1) and it u do binary anding of ot it with just a number previous to it ,then u will get Zeros
    For example
    8=1000(binary form ) here u can see only one (bit 1) is there rest are zeros
    Now the number just previous to 8 is 7
    so, 7=0111 and if u perform anding operation on it as
    1000(8)
    (AND) 0111(7)
    ---------
    0000(0)
    ---------
    So if we perform AND operation between the number (which we want to check is a power of two or not) and the number just previous to it and result comes as zeros then its power of two otherwise it s not.
    PROGRAM(IN C_LANGUAGE)
    #include
    #include
    main()
    {
    int num, num1,sum;
    clrscr();
    printf("Enter the number");
    scanf("%d",&num);
    printf("\nEntered number=%d",num);
    num1=num-1;
    sum=num & num1;
    if(sum==0)
    printf("\n Entered number is power of two");
    else
    printf("\n Entered number is not power of two");
    getch();

    ReplyDelete
  5. This really answered my problem, thanks! gsn casino slots

    ReplyDelete