leetcode刷题,总结, 记录,备忘326

来源:互联网 发布:c语言 面向过程 编辑:程序博客网 时间:2024/05/22 03:39

leetcode326Power 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?

使用递归或者循环是很简单的。

class Solution {public:    bool isPowerOfThree(int n) {        if (n <= 0)        {            return false;        }        if (n == 1)        {            return true;        }                return n % 3 == 0 && isPowerOfThree(n / 3);    }};
题目中有比较高的要求不使用递归或者循环,那该怎么办呢,看了leetcode的几个高投票的答案。
class Solution {public:    bool isPowerOfThree(int n) {        double t = log10(n) / log10(3);        if (t == (int)t)        {            return true;        }        else        {            return false;        }    }};
使用对数计算的方式,我特地去会议了下中学时学习的对数计算公式,在此做个例子就很好理解了。比如log10(3)和log10(9),log10(9) = log10(3x3) = log10(3) + log10(3);所以如果n是3的指数次幂的话,log10(n)的值一定是log10(3)的整数倍,很好理解了吧,科科。


0 0
原创粉丝点击