IsPowerOf2
Returns true if the given number is a power of 2, false otherwise.
- Use the bitwise binary AND operator (
&) to determine ifnis a power of2. - Additionally, check that
nis non-zero.
func IsPowerOf2(n int) bool {
return n > 0 && (n&(n-1)) == 0
}IsPowerOf2(0) // false
IsPowerOf2(1) // true
IsPowerOf2(8) // true