题目链接
https://leetcode.com/problems/ugly-number/
题目原文
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include
2, 3, 5
. For example,6
,8
are ugly while14
is not ugly since it includes another prime factor7
.Note that
1
is typically treated as an ugly number.
题目翻译
编程判断一个给定的数是否是“ugly number”。
所谓“ugly number”是指质因数仅包含在 2,3,5 中的正数。比如,6和8都是“ugly number”,而14不是,因为14包含7这个质因数。
注意,1 也被认为是”ugly number”。
思路方法
思路一
根据定义,依次将所给的数除以 2,3,5 直至无法除尽,如果这时得到1则说明所给的数的质因子不超出2,3,5三个数,否则说明有其他质因数。
代码一
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0:
return False
for i in [2, 3, 5]:
while num%i == 0:
num = num / i
return True if num == 1 else False
思路不变,该题不用迭代法而用递归也可以实现。
代码二
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0:
return False
if num == 1:
return True
if num % 2 == 0:
return self.isUgly(num/2)
elif num % 3 == 0:
r