题目
题干
该问题3的幂 题面:
Given an integer n, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three, if there exists an integer x such that n == 3x.
给定一个整数,写一个函数来判断它是否是 3 的幂次方。如果是,返回 true ;否则,返回 false 。
整数 n 是 3 的幂次方需满足:存在整数 x 使得 n = = 3 x n==3^x n==3x
示例
示例 1:
输入:n = 27
输出:true
示例 2:
输入:n = 0
输出:false
示例 3:
输入:n = 9
输出:true
示例 4:
输入:n = 45
输出:false
题解
解法1:循环
C++
class Solution1 {
public:
bool isPowerOfThree(int n) {
if(n==1) return true;
long m=1;
while(m<n)
{
m*=3;
if(m==n)
return true;
}
return false;
}
};
Python
class Solution1:
def __init__(self,n):
self.n = n
def isPowerOfThree(self):
if self.n == 1:
return True
m = 1
while m<self.n:
m *=3
if m==self.n:
return True
return False
解法2:递归
C++
class Solution2 {
public:
bool isPowerOfThree(int n) {
if(n==1) return true;
else if(n==0) return false;
else return isPowerOfThree(n/3)&&n%3==0;
}
};
Python
class Solution2:
def __init__(self):
pass
def isPowerOfThree(self,n):
if n == 1:
return True
elif n == 0:
return False
else:
return self.isPowerOfThree(n//3) and (n%3) == 0
解法3:范化
3的幂次质因子只有3,而整数范围内的3的幂次最大是1162261467
C++
class Solution3 {
public:
bool isPowerOfThree(int n) {
return n > 0 && 1162261467%n == 0;
}
};
Python
class Solution3:
def __init__(self, n) -> None:
self.n = n
def isPowerOfThree(self):
return self.n > 0 and 1162261467%self.n == 0