Interview Question
Software Engineer in TestsCountry: England
Interview Type: Phone Interview
Classic ol' trick. For those who don't know, the reason it works is because a power of two has the binary form 1000000... (with some number of 0s). The number minus 1 has the form 0111111...(with the corresponding number of 1s). Therefore ANDing the two would yield 0. This can only be true of powers of two because for any number that has any digits after the leading 1, both n and n-1 would have the leading one in the same place.
'0' isn't power of two. More correct version.
boolean isPowerOfTwo(int value){
return value > 0 && (value & (value-1)) == 0;
}
(n & (n-1) == 0) => n is power of 2
- Arun April 17, 2012