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?

答案:

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

     因为3是一个素数,所以一个数如果是3的幂,则它的任何约数也是3的幂。

     所以思路是求出int型的最大的3的幂,除以我们需要判断的数,如果余数为0,则该数为3的幂。

     或者用long long求一个比int的最大值还大的3的幂也可以。

1 class Solution {
2 public:
3     bool isPowerOfThree(int n) {
4         int max,m;
5         max=(numeric_limits<int>::max)(); 
6         m=pow(3,((int)(log(max)/log(3))));
7             return(n>0&& (m%n==0));
8     }
9 };

注意:^是位运算中的异或符号,不是求幂的符号。

原文地址:https://www.cnblogs.com/Reindeer/p/5639081.html