Leetcode 231, 326, 342 Power of two, three, four

 Given an integer, write a function to determine if it is a power of two.

Hint:

  1. Could you solve it in O(1) time and using O(1) space?

最容易想到的方法是用n反复的去除以2,一直到n变成1。这期间如果出现不能被2整除的数,那么一开始的n就不是2的power.

 1 class Solution(object):
 2     def isPowerOfTwo(self, n):
 3         """
 4         :type n: int
 5         :rtype: bool
 6         """
 7         if n <= 0:
 8             return False
 9         
10         while n > 1:
11             if n % 2 == 1:
12                 return False
13             else:
14                 n = n/2
15         return True

但是为了满足O(1)的time and space complexity, 可以使用位操作。因为2的power变成二进制时就是第一位是1后面都是0。

2 = 10, 4 = 100,8 = 1000, ... 那么 n-1 除了第一位是0,其他全是1。使用 & (bitwise AND)

1     return n > 0 and n & (n -1) == 0

 

判断一个数是不是3的power,可以用同样的思路。

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0:
            return False

        while n > 1:
            if n % 3 > 0:
                return False
            else:
                n = n/3
        return True    

 

判断一个数是不是4的power。由于要求不能使用loop。4^a - 1 = (2^a + 1)(2^a - 1)。这两个相邻的奇数中肯定有一个是3的倍数。

return num > 0 and num & (num - 1) == 0 and (num - 1)%3 == 0

 

posted @ 2016-12-13 13:18  lettuan  阅读(111)  评论(0编辑  收藏  举报