Leetcode #326:3的幂

题目

题干

该问题3的幂 题面:

Given an integer n, return true if it is a power of three. Otherwise, return false.

An integer n is a power of three, if there exists an integer x such that n == 3x.

给定一个整数,写一个函数来判断它是否是 3 的幂次方。如果是,返回 true ;否则,返回 false 。

整数 n 是 3 的幂次方需满足:存在整数 x 使得 n = = 3 x n==3^x n==3x

示例

示例 1:

输入:n = 27

输出:true

示例 2:

输入:n = 0

输出:false

示例 3:

输入:n = 9

输出:true

示例 4:

输入:n = 45

输出:false

题解

解法1:循环

C++

class Solution1 {
public:
    bool isPowerOfThree(int n) {
        if(n==1) return true;
        long m=1;
        while(m<n)
        {
            m*=3;
            if(m==n)
                return true;
        }
        return false;
    }
};

Python

class Solution1:
    def __init__(self,n):
        self.n = n
    
    def isPowerOfThree(self):
        if self.n == 1:
            return True
        m = 1
        while m<self.n:
            m *=3
            if m==self.n:
                return True
        return False

解法2:递归

C++

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

Python

class Solution2:
    def __init__(self):
        pass
    
    def isPowerOfThree(self,n):
        if n == 1:
            return True
        elif n == 0:
            return False
        else:
            return self.isPowerOfThree(n//3) and (n%3) == 0

解法3:范化

3的幂次质因子只有3,而整数范围内的3的幂次最大是1162261467

C++

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

Python

class Solution3:
    def __init__(self, n) -> None:
        self.n = n
    
    def isPowerOfThree(self):
        return self.n > 0 and 1162261467%self.n == 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值