326. Power of Three LeetCode解题报告

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?
解法一:采用循环,O(lg(N))的速度

class Solution {
public:
    bool isPowerOfThree(int n) {

       if (n == 1 || n == 3 )
            return true;
        if (n<3)
            return false;

        int i = 2;
        while(true)
        {
            if(pow(3,i) ==n)
                return true;
            else if (pow(3,i) > n)
                return false;
            else
                ++i;
        }




    }
};

解法二:采用递归方法

class Solution {

public:
  bool isPow3(int n, int step){
          if(pow(3,step) == n)
                return true;
            else if(pow(3,step) > n)
                return false;
            else
                return  isPow3(n,++step);
      }

    bool isPowerOfThree(int n) {
        int step = 0;
        return isPow3(n,step);





    }
};

解法三

return n>0 ? !(1162261467%n):0;

解法四

return (n == 1 || n == 3 || n == 9 || n == 27 || n == 81 || n == 243 || n == 729 || n == 2187 || n == 6561 || n == 19683 || n == 59049 || n == 177147 || n == 531441 || n == 1594323 || n == 4782969 || n == 14348907 || n == 43046721 || n == 129140163 || n == 387420489 || n == 1162261467);  

解法5

bool isPowerOfThree(int n) { double logRes = log10(n)/log10(3); return (logRes - int(logRes) == 0) ? true : false; }

The code implements the base change rule of the logarithm. it basically looks at if base3 logarithm of the number is an integer or not.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值