Leetcode刷题115-326. 3的幂(C++最简单实现详细解法!!!)

Come from : [https://leetcode-cn.com/problems/power-of-three/]

1.Question

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?

2.Answer

easy类型题目。。。

AC代码如下(简单循环):

class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n<=0) return false;
        if(n==1) return true;
        while(n>1)
        {
            if(n%3 != 0) return false;
            n = n/3;
        }
        return true;
    }
};

3.大神解答

方法1:递归

class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n==1) return true;
        else if(n==0) return false;
        else return isPowerOfThree(n/3) && n%3 == 0;
    }
};

方法2:不用循环或递归的做法
3的幂次质因子只有3,而整数范围内的3的幂次最大是1162261467

class Solution {
public:
    bool isPowerOfThree(int n) {
        return n > 0 && 1162261467%n == 0;
    }
};

作者:gpe3DBjDS1
链接:https://leetcode-cn.com/problems/two-sum/solution/3de-mi-by-gpe3dbjds1/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

4.我的收获

fighting。。。

2019/7/5 胡云层 于南京 115

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值