1-liners other than the boring n&n-1 :-P


  • 2

    C++

    Using how doubles represent numbers.

    bool isPowerOfTwo(double n) {
        return n > 0 && !(*(long long*)&n << 12);
    }
    

    Python Golf

    Using n&-n and chained comparisons.

    def isPowerOfTwo(self, n):
        return-n&n==n>0
    

    Python

    Assigning a set's method.

    class Solution:
        isPowerOfTwo = {1<<e for e in range(31)}.__contains__

  • 0
    P

    Wooow~ How you discover this? The double type contains 64 bits: 1 for sign, 11 for the exponent, and 52 for the mantissa. Its range is +/–1.7E308 with at least 15 digits of precision. This is how "12" comes. If the number is the power of two, then mantissa part would be 0 which stands for 1.0


  • 0

    Yep, that's how it works. I've done something like this a few times, you just need to know a bit about the double format, and every coder should :-). The first time, I needed the log2 of an int and I couldn't use a log function. So I made it a double and extracted the exponent.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.