-1

I know this method and it is not efficient enough

(a/2)%2==0;
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
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
  • 90,870
  • 19
  • 190
  • 224
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
  • 46,822
  • 11
  • 79
  • 123
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
  • 9,064
  • 3
  • 31
  • 49