326. Power of Three

来源:互联网 发布:js杀破狼无损百度云 编辑:程序博客网 时间:2024/06/05 09:14

326. Power of Three

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

Follow up:

Could you do it without using any loop / recursion?

判断一个数是否是3的幂,不适用循环和递归

利用对数换底公式,logab= logcb / logca。

log3n = log10n / log103,那么他们的商log3n一定是整数。

C++中判断一个数是否为整数 a - int(a) =0则为整数。

 

class Solution {public:    bool isPowerOfThree(int n){          returnint(log10(n)/log10(3))-(log10(n)/log10(3))==0;    }};


而由于是INT型的,整数范围是0-231,所以,先求得在此范围内的最大的3的幂,是1162261467(拓展,在Java中可以 Integer.MAX_VALUE=2147483647

class Solution {public:    bool isPowerOfThree(int n){          return (n>0 && 1162261467%n==0);    }}; 


原创粉丝点击