LintCode 1294: Power of Three

本文介绍了一种方法,用于确定一个给定的整数是否可以表示为3的幂次方。提供了两种解决方案,一种使用循环逐步乘以3进行比较,另一种采用递归方式除以3直到无法整除。这两种方法都有效地解决了问题,但递归方法可能在某些情况下更简洁。

1294. Power of Three

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

Example

Example1

Input: n = 0
Output: False

Example2

Input: n = 9
Output: True

Challenge

Could you do it without using any loop / recursion?

Input test data (one parameter per line)How to understand a testcase?

解法1:
 

class Solution {
public:
    /**
     * @param n: an integer
     * @return: if n is a power of three
     */
    bool isPowerOfThree(int n) {
        int num = 1;
        while(num <= n) {
            if (num == n) return true;
            num *= 3;
        }
        return false;
    }
};

解法2:

class Solution {
public:
    /**
     * @param n: an integer
     * @return: if n is a power of three
     */
    bool isPowerOfThree(int n) {
        if (n == 0 || n == 1) return n;
        if (n % 3 != 0) return false;
        return isPowerOfThree(n / 3);
    }
};


 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值