您的位置:首页 > 职场人生

leetcode之power of three

2016-01-21 15:18 281 查看
题目:

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的次方得到,首先这个数必须是正数,其次以log3(num)必定是正数

这样就可以不用循环就得到结果

class Solution {

public:

    bool isPowerOfThree(int n) {

        if(n <= 0)

            return false;

        return n == pow(3, round(log(n) / log(3)));

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法 面试