【leetcode】326. power of three 以及 log 问题

版权声明:来自 T2777 ,请访问 https://blog.csdn.net/T2777 一起交流进步吧 https://blog.csdn.net/T2777/article/details/87182294

首先介绍 c++ 中 math.h 中的 log 函数的用法, log 函数只支持 double log10(double x) 以及double log(double x) 两种形式,

其中 log10(x)以 10 为底,log(x)则以 e 为底,想要求其它的对数,要用 log(y) / log(x) 的形式,这在数学上很好理解,不再详细解释。

题目描述:

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

Example 1:

Input: 27
Output: true

Example 2:

Input: 0
Output: false

Example 3:

Input: 9
Output: true

Example 4:

Input: 45
Output: false

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

题目要求不要用循环,考虑到 3 的幂不好从位的规律上来解决,那么就暴力的解决,在int 范围内,找到最大的3的幂big3,那么所给的 n 当为 3 的幂时,必须是big3的因数,可以整除,3,9,27,81,后面的一定可以整除前面的,这是必然的

但是要注意的是,这种方法可以用到  2 和 3 这种质数上,但用到 4 肯定不对了,比如 4 的幂可能可以整除 2 的幂,这点要注意

代码:

class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n <= 0)
            return false;
        const int maxint = 0x7fffffff;
        int k = log(maxint)/log(3);
        //log得到的是double型,而int k 做了强制类型转换,向下取整
        //再通过下面的方式得到确切的int范围的3的最大幂即可
        int big3 = pow(3,k);
        return (big3 % n == 0);
    }
};

 不得不吐槽一下 leetcode,同一个代码运行两次的速度反而不同,嘻嘻。

猜你喜欢

转载自blog.csdn.net/T2777/article/details/87182294