-1

I know this method and it is not efficient enough

(a/2)%2==0;
Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021
g.i joe
  • 11
  • 4

3 Answers3

6

See the Bit Twiddling Hacks :

unsigned int v; // we want to see if v is a power of 2
bool f;         // the result goes here 

f = (v & (v - 1)) == 0;

Note that 0 is incorrectly considered a power of 2 here. To remedy this, use:

f = v && !(v & (v - 1));
DarkDust
  • 87,789
  • 19
  • 183
  • 216
4

Your method does not check that. It will return true for 12 for example.(and will return false for 2)

To check you may use x != 0 && (x & (x - 1)) == 0

RiaD
  • 45,211
  • 10
  • 74
  • 119
3

If you're using gcc and x64 there's an intrinsic that lets you use the CPU instruction that counts bits:

int __builtin_popcount (unsigned int x)
James
  • 8,897
  • 2
  • 28
  • 47