leetcode-326-Power-of-Three

描述


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

Follow up:
Could you do it without using any loop / recursion?

分析


我记得以前有写过这样的题目,所以就随手写出来了,,,C语言的版本是评论区里见到的,简直是神代码,原理是这样的:$2^31 - 1= 1162261467 $,而$1162261467=3^19$,所以在c中,能被1162261467整除的,一定是3的某次幂

解决方案1(C)


1
2
3
bool isPowerOfThree(int n) {
return (n>0 && 1162261467%n==0);
}

解决方案2(C++)


1
2
3
4
5
6
7
class Solution {
public:
bool isPowerOfThree(int n) {
double logres = log10(n) / log10(3);
return (logres == int(logres))? true: false;
}
};

解决方案3(Python)


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

相关问题


(E) Power of Two

题目来源