ling ling - 21 days ago 5
Java Question

Power of two failed to pass the test

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

boolean isPowerOfTwo(int n) {
return (n%2==0);
}

snr snr
Answer

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 & -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;
}
Comments