LeetCode--231--2的幂函

问题描述:

给定一个整数,编写一个函数来判断它是否是 2 的幂次方。

示例 1:

输入: 1
输出: true
解释: 2

0

 = 1

示例 2:

输入: 16
输出: true
解释: 2

4

 = 16

示例 3:

输入: 218
输出: false

方法1:

 1 import math
 2 class Solution(object):
 3     def isPowerOfTwo(self, n):
 4         """
 5         :type n: int
 6         :rtype: bool
 7         """
 8         if n % 2 != 0 and n != 1 or n < 0 :
 9             return False
10         width = int((math.sqrt(n)))
11         for i in range(width+2):
12             if math.pow(2,i) == n:
13                 return True
14             elif math.pow(2,i) > n:
15                 return False
16         return False

方法2:二进制

 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         return bin(n).count('1') == 1

方法3:

1 class Solution(object):
2     def isPowerOfTwo(self, n):
3         """
4         :type n: int
5         :rtype: bool
6         """
7         while n%2 == 0 and n>1:
8             n = n/2
9         return (n==1)

2018-09-20 06:58:15

posted @ 2018-09-20 06:59  Assange  阅读(190)  评论(0编辑  收藏  举报