Determine if int is power 2 or not on one line

Possible duplicate:
How to check if a number is power 2

I made the following code, but it does not work. The compiler gives an error message for the missing error )and expression syntax. What is the operator procedure? Left to right or right to left?

#include <stdio.h>
#include <limits.h>
#include <math.h>
int main()
{
    int i, x = 256, y, flag;
    for (i = 0, flag = 0, y = 1; y<INT_MAX; if (flag) break, if (flag) printf("YES"), if(y == x) flag = 1, i++, y = pow(2,i));
    return 0;
}
+3
source share
4 answers
 bool ispowerof2(unsigned int x) {
   return x && !(x & (x - 1));
 }

Please note that the bit-bit of the power of two has the form 10 ... 0, and a number from a number equal to one less is 011 ... 1.

As for your code:

for( i=0, flag=0, y=1;
     y<INT_MAX;      
     if(flag)break,if(flag)printf("YES"),if(y==x)flag=1,i++,y=pow(2,i)
   );

The last part foris illegal.

+20
source

, , , , , , . , , .

+8

:

bool isPow2 = ((x & ~(x-1))==x)? x : 0;

, , 2.

+3

, `if (flag) printf ( "YES" ) .

, , (val != 0) && ((val & val-1) == 0) , .

+1

Source: https://habr.com/ru/post/1763141/


All Articles