[Python] Count '1' in binary, 1 line


  • 3
    D
    class Solution(object):
        def isPowerOfTwo(self, n):
            return n > 0 and bin(n).count('1') == 1
    

    More readable than n & (n - 1)


  • 0
    W

    yeah, you are right. so simple and more readable


  • 0
    S

    Although the solution is more readable, the interview purpose to check your knowledge of binary numbers, instead of Python or other language's library usage. A further question would be solution without built-in library.


Log in to reply
 

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