栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Leetcode #326:3的幂

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Leetcode #326:3的幂

Leetcode #326:3的幂
  • 题目
    • 题干
    • 示例
      • 示例 1:
      • 示例 2:
      • 示例 3:
      • 示例 4:
  • 题解
    • 解法1:循环
      • C++
      • Python
    • 解法2:递归
      • C++
      • Python
    • 解法3:范化
      • C++
      • Python

题目 题干

该问题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 
Python 
class Solution1:
    def __init__(self,n):
        self.n = n
    
    def isPowerOfThree(self):
        if self.n == 1:
            return True
        m = 1
        while m 
解法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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/348543.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号