LeetCode刷题实战326: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.

示例
示例 1:
输入:n = 27
输出:true
示例 2:
输入:n = 0
输出:false
示例 3:
输入:n = 9
输出:true
示例 4:
输入:n = 45
输出:false
解题
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;
}
};
public:
bool isPowerOfThree(int n) {
if(n==1) return true;
else if(n==0) return false;
else return isPowerOfThree(n/3)&&n%3==0;
}
};
class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && 1162261467%n == 0;
}
};
赞 (0)