LeetCode #231 #326 #342 2018-08-04

231. Power of Two

https://leetcode.com/problems/power-of-two/description/

n如果是2的平方,那二进制的n中必然只有一位是1,所以可以通过n&(n-1)==0来判断n是否符合题意。
代码如下:

class Solution:
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n > 0 and not n&(n - 1)

326. Power of Three

https://leetcode.com/problems/power-of-three/description/

正常来说,还是可以使用递归或者迭代的方式来解。
递归代码如下:

class Solution:
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n > 0 and (n == 1 or (n % 3 == 0 and self.isPowerOfThree(n / 3)))

迭代代码如下:

class Solution:
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n > 1:
            while not n % 3:
                n /= 3
        return n == 1

找到在不越界的情况下最大的3的n次幂,然后检查它是否为n的倍数
代码如下:

class Solution:
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        # maxNum = 1
        # while maxNum <= (1 << 31) - 1:
        #     maxNum *= 3
        # maxNum /= 3
        return n > 0 and not 1162261467 % n

检查log10(n) / log10(3)是否为一个整数
代码如下:

class Solution:
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        import math
        return n > 0 and not (math.log10(n) / math.log10(3)) % 1

342. Power of Four

https://leetcode.com/problems/power-of-four/description/

上道题中的递归迭代以及log方法都试用于这道题,这里就不再赘述。
提供一个独特的方式。参考Python one line solution with explanations.
代码如下:

class Solution:
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        # mask = 1
        # for i in range(1, 16):
        #     mask = (mask << 2) + 1
        return num != 0 and not num&(num - 1) and num & 1431655765 == num

你可能感兴趣的:(LeetCode #231 #326 #342 2018-08-04)