[LeetCode][Python]231. Power of Two

538 ワード

Given an integer, write a function to determine if it is a power of two.
問題解決の考え方:
簡単そうな問題なのに、最初は何の考えもなかった.でもヒントを見て自分でまたn&(n-1)を忘れてしまいました.(n&(n−1)==0の意味で、nの最高有効ビットは1であり、残りのビットは0である.したがって,nの値は2のある次数である.したがって,(n&(n−1)==0 nが2であるか否かのいずれかを検査する(またはnが0であるか否かを検査する)=0
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return (n>0 and n&(n-1)==0)