【力扣题】题目描述:
此题:正整数n,能被2或3或5整除,且不断除以2或3或5最终的数是1。
【Python3】代码:
1、解题思路:递归。
知识点:递归:函数中调用函数自身(必须有退出条件,否则无限调用)
class Solution:def isUgly(self, n: int) -> bool:if n <= 0: return Falseelif n == 1: return Trueelif n % 2 == 0: return self.isUgly(n/2)elif n % 3 == 0: return self.isUgly(n/3)elif n % 5 == 0: return self.isUgly(n/5)else: return False
2、解题思路:循环。
class Solution:def isUgly(self, n: int) -> bool:if n <= 0: return Falsea = [2,3,5]for x in a:while n % x == 0:n /= xreturn n == 1# 或者if n <= 0: return Falsewhile n % 2 == 0: n /=2while n % 3 == 0: n /= 3while n % 5 == 0: n /=5return n == 1# 或者if n <= 0: return Falsewhile True:if n % 2 == 0: n /=2elif n % 3 == 0: n /= 3elif n % 5 == 0: n /=5elif n == 1: return Trueelse: return False