您的位置:首页 > 编程语言 > Python开发

46 leetcode - 如何快速判断一个数是不是2的幂、3的幂、4的幂

2016-12-19 13:58 381 查看

判断一个数是不是2的幂

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Power of Two
Given an integer, write a function to determine if it is a power of two.
判断一个数是否等于pow(2,n).
如果一个数等于pow(2,n),则2进制表达中,有且仅有一个1。n & (n-1) == 0
'''
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False
return True if n&(n-1) == 0 else False


判断一个数是不是4的幂

4的幂首先是2的幂,因为4^n = (2^2)^n,所以4的幂的二进制同样只有一个1,与2的幂不同的是,4的幂的二进制的1在奇数位上,所以判断一个数是不是4的幂的方式为:

1)首先判断是不是2的幂,使用 n & (n-1)

2)进一步判断与0x55555555的按位与结果,0x55555555是用十六进制表示的数,其奇数位上全是1,偶数位上全是0,判断 n & 0x55555555

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

if num & (num - 1) != 0:
return False

return False if num & 0x55555555 == 0 else True


判断一个数是不是3的幂

'''
Power of Three
Given an integer, write a function to determine if it is a power of three.
判断一个数是否等于pow(3,n).
'''
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False
max_3_pow = 0
while pow(3,max_3_pow + 1) <= n:
max_3_pow += 1

return True if n == pow(3,max_3_pow) else False


还有一种很机智的方法,我们首先分析3的幂的特点,假设一个数Num是3的幂,那么所有Num的约数都是3的幂,如果一个数n小于Num且是3的幂,那么这个数n一定是Num的约数。

了解上述性质,我们只需要找到一个最大的3的幂,看看参数n是不是此最大的幂的约数就行了.

class Solution(object):
'''
找到一个最大的3的幂
a = pow(2,31) - 1,最大的正整数
import math
math.log(a,3),19.5588223603
最大的3的幂 = pow(3,19) = 1162261467
'''

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

return True if 1162261467%n == 0 else False


参考链接:http://blog.csdn.net/x_i_y_u_e/article/details/50507281
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息