Power of Two

Another beautiful solution to an easy LC problem.

class Solution {
    fun isPowerOfTwo(n: Int): Boolean = if(n and Integer.MAX_VALUE == 0) false else Integer.bitCount(n) == 1
}
Runtime: 124 ms, faster than 82.61% of Kotlin online submissions for Power of Two.
Memory Usage: 31.3 MB, less than 100.00% of Kotlin online submissions for Power of Two.

The solution is short and simple. The first check is for integer overflow. One of the input values is the overflowed integer value, -2147483648. This is the value used to represent a number whose value exceeds Integer.MAX_VALUE.

In binary, this can be represented as 100000000. Since integer uses only 8 bits, the overflow value is equivalent to 00000000. To check if the input value is an overflowed integer, we can simply AND the input with Integer.MAX_VALUE (11111111). If it is 0 then it’s either the input is zero or the overflow.

For other cases, we just count the number of bits. If it is 1 then the input is a power of 2.

For example:

0001 or 1 is a valid power of 2

0010 or 2 is a valid power of 2

0100 or 4 is a valid power of 2

1000 or 16 is a valid power of 2

As you can see in the pattern, a number is a valid power of two if there’s only 1 bit that is set.