Google Interview Question

Write an algorithm to test if n is power of 2

Interview Answers

Anonymous

Sep 25, 2010

I believe what the other poster meant was the following: !(n & (n-1)) !(n & 0x00000001) is equivalent to !(n&1) and is independent of integer size. However, this only checks if a number is even.

6

Anonymous

Jan 23, 2011

if the range is within a 32bit signed integer, you can check as following way if (n == (n & -n)) return true; else return false;

1

Anonymous

Sep 24, 2010

! (n & 0x00000001) assuming 32 bit integer