leetcode 326. Power of Three 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?

最直接的方法是使用log函数,还有一个从网上看到的别的方法,也可以,不过很难想。

建议和这一道题leetcode 342. Power of Four 4的幂指数 一起学习。

代码如下:

/*
 * 使用3的幂数的相关解法,使用log很不错,第二个也很不错
 * */
public class Solution 
{
    public boolean isPowerOfThreeByLog(int n) 
    {
        double res=Math.log10(n) / Math.log10(3);
        return (res-(int)(res))==0?true:false;
    }

    public boolean isPowerOfThree(int n) 
    {
        // 1162261467 is 3^19,  3^20 is bigger than int  
        return ( n>0 &&  1162261467%n==0);
    }
}

下面是C++的做法,很简单直接求对数即可

代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>

using namespace std;



class Solution 
{
public:
    bool isPowerOfThree(int n)
    {
        double res = log10(n) / log10(3);
        return (res - (int)(res) == 0) ? true : false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值