Leetcode 263.丑数
1 题目描述(Leetcode题目链接)
编写一个程序判断给定的数是否为丑数。丑数就是只包含质因数 2, 3, 5 的正整数。示例:
输入: 6
输出: true
解释: 6 = 2 × 3
输入: 8
输出: true
解释: 8 = 2 × 2 × 2
输入: 14
输出: false
解释: 14 不是丑数,因为它包含了另外一个质因数 7。
说明:
- 1 是丑数。
- 输入不会超过 32 位有符号整数的范围: [ − 2 31 , 2 31 − 1 ] [−2^{31}, 2^{31} − 1] [−231,231−1]。
2 题解
本题是数学问题,如果是丑数则一直除以2、3、5最终得到的答案是1。如果最终得到的答案不是1就说明不是丑数。
递归:
class Solution:
def isUgly(self, num: int) -> bool:
if num == 1:
return True
if (num % 2 != 0 and num % 3 != 0 and num % 5 != 0) or num == 0:
return False
return self.isUgly(num/2) or self.isUgly(num/3) or self.isUgly(num/5)
非递归:
class Solution:
def isUgly(self, num: int) -> bool:
if num < 1:
return False
for i in [2, 3, 5]:
while num % i == 0:
num /= i
return num == 1