326. Power of Three(easy)

本文介绍了一种方法,用于判断一个给定的整数是否可以表示为3的幂次方。提供了两种解决方案,一种是通过循环除以3的方法,另一种是使用换底公式计算对数的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Easy

3241153FavoriteShare

Given an integer, write a function to determine if it is a power of three.

Example 1:

Input: 27

Output: true

Example 2:

Input: 0

Output: false

Example 3:

Input: 9

Output: true

Example 4:

Input: 45

Output: false

Follow up:
Could you do it without using any loop / recursion?

 

循环除法:

C++ :

/*
 * @Autor: SourDumplings
 * @Date: 2019-09-10 20:21:54
 * @Link: https://github.com/SourDumplings/
 * @Email: changzheng300@foxmail.com
 * @Description: https://leetcode.com/problems/power-of-three/
 */

class Solution
{
public:
    bool isPowerOfThree(int n)
    {
        while (n > 1 && n % 3 == 0)
        {
            n /= 3;
        }
        return n == 1;
    }
};

换底公式法1:

Java:

/*
 * @Autor: SourDumplings
 * @Date: 2019-09-10 20:32:57
 * @Link: https://github.com/SourDumplings/
 * @Email: changzheng300@foxmail.com
 * @Description: https://leetcode.com/problems/power-of-three/
 * 
 * 设3^i = n,则i = log3(n) = log10(n) / log10(3)
 * 判断这样得到的3^i还是不是n,或者i是不是整数即可(用 % 1判断)
 */

class Solution
{
    public boolean isPowerOfThree(int n)
    {
        return n != 0 && (Math.log10(n) / Math.log10(3)) % 1 == 0;
    }
}

换底公式法2:

Java:

/*
 * @Autor: SourDumplings
 * @Date: 2019-09-10 20:32:57
 * @Link: https://github.com/SourDumplings/
 * @Email: changzheng300@foxmail.com
 * @Description: https://leetcode.com/problems/power-of-three/
 * 
 * 设3^i = n,则i = log3(n) = log10(n) / log10(3)
 * 判断这样得到的3^i还是不是n,或者i是不是整数即可(用 % 1判断)
 */

class Solution
{
    public boolean isPowerOfThree(int n)
    {
        if (n == 0)
            return false;
        int i = (int) (Math.log10(n) / Math.log10(3));
        return Math.pow(3, i) == n;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值