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