-6

Isn't this one way to test whether a number is a power of 2?

boolean isPowerOfTwo(int n) {
        return (n%2==0);
    }
ling
  • 1,555
  • 3
  • 18
  • 24

3 Answers3

1

Are you sure that you are checking power of 2? Rather, being checked divisible with 2. If you are serious, use the piece of cake snippet

return n > 0 && ((n & -n) == n);

The second way,

enter image description here

private static boolean powerOf2(int num)
{
  if(num <= 0){
   return false;
  }

  while(num > 1)
  {
   if(num % 2 != 0)
   {
    return false;
   }
   num = num / 2;
  }
  return true;
}
1

That function checks whether or not an integer is even (i.e divisible by 2), not whether or not the integer is a power of 2.

To check if a number is a power of 2, you should look at its bits. ints that are a power of 2 will have one bit set to 1 and all others set to 0.

boolean isPowerOf2(int i) {
    return Integer.bitCount(i) == 1;
}
The SE I loved is dead
  • 1,517
  • 4
  • 23
  • 27
0

The % is the modulo operator, meaning the remainder after division. your method checks if the int n is divisible by 2

GerritCap
  • 1,606
  • 10
  • 9
  • So my code is a necessary, but insufficient condition of being as a power of 2. right? – ling Nov 13 '16 at 16:22
  • I would not put it in the "necessary" category, you are just checking if the number is dividable by 2 not if it is a power of 2. It is just doing something different. There is however a binary rule: if the binary version of your int only has one 1 digit, then it is a power of 2. This can be checked with a boolean operator n & (n - 1) == 0 – GerritCap Nov 13 '16 at 16:33
  • i mean it must be divisible by 2, which is necessary. – ling Nov 13 '16 at 16:40
  • @ling Powers of 2 are actually a subset of even numbers - if you figure out that an integer is a power of 2, you don't need to check if the same integer is even. – The SE I loved is dead Nov 13 '16 at 16:57