您的位置:首页 > 其它

<LeetCode OJ> 326. Power of Three

2016-01-08 22:44 681 查看


326. Power of Three

My Submissions

Question

Total Accepted: 1159 Total
Submissions: 3275 Difficulty: Easy

判断给定整数是否是3的某次方。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?完成此题,您敢不敢不用迭代或者循环?(那就是递归了呗)
Credits:

Special thanks to @dietpepsi for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
Math

Hide Similar Problems
(E) Power of Two

最简单的方法,反复迭代,O(lg(N))的速度

//思路首先:3^x,不管x正负,这个值一定大于0
//如果一个数是3的x次方那么,那么递增i,n一定会在i为某个值等待pow(3,i)完全相等
class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n==1 || n==3)
            return true;
        if( n<3 )
            return false;
        int i=1;    
        while(true)
        {
            if(pow(3,i)==n)
                return true;
            if(pow(3,i)>n)
                return false;
            if(pow(3,i)<n)
                i++;
        }
    }
};


和上面的思想一样:递归形式的解法

//思路首先:3^x,不管x正负,这个值一定大于0
//如果一个数是3的x次方那么,那么递增i,n一定会在i为某个值等待pow(3,i)完全相等
//递归形式的解法
class Solution {
public:
   
    bool isPow3(int n,int step) {
        if(pow(3,step)==n)  
                return true;  
        if(pow(3,step)>n)  
                return false;  
        if(pow(3,step)<n)  
                return isPow3(n,++step); 
    }
    bool isPowerOfThree(int n) {
        int step=0;
        return isPow3(n,step);
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: