One line python code that beats almost all solution


  • 0
    C
    class Solution(object):
        def isPowerOfFour(self, num):
            """
            :type num: int
            :rtype: bool
            """
            return not ( num == 0 or num & num -1 or num & 2863311530 )
    

    For a number to be 4 **n , it has the following attributes:

    1. In its bit representation, only one location is 1, this is obtained via num & num - 1
    2. The bits 1 could only occur in location0, 2,4,6,8...,30, this is obtained via num & 2863311530

  • 0

    What do you mean with "beats almost all solution"? I submitted it three times and was told it beats 41%, 27%, 27%.


  • 0
    C

    @StefanPochmann When I submit the solution, the OJ says something like 'share your result to others so others can challenge you' and I did not see the usual percentage telling me how well the solution is ahead of the others, and that tricks me into thinking the solution is optimal.
    I tried again, and you are right, the tile is a little misleading.


  • 0

    @churchmice Hmm, strange, I think the only times I didn't see the usual percentage message were when my solution was off the chart slow. But that shouldn't happen with yours. And it also shouldn't be off the chart fast, as that would mean a negative time :-)

    Anyway, Python times vary a lot here even for the exact same code, so they're not really reliable (unless you submit several times and see a significant pattern).


Log in to reply
 

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