263. Ugly Number
problem
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 while 14 is not ugly since it includes another prime factor 7.
Note that 1 is typically treated as an ugly number.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
判断数字的最小因数是不是只有2,3,5; 是True,不是false
数字1视为True
solution
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
factors = [2,3,5]
for i in factors:
while 1:
x, y = divmod(num,i)
if y > 0:
break
else:
num = x
return num == 1
直接除法运算, time limit exceeded
换一个思路,反过来,可以整除其他素数则返回False,问题转化为获取素数列表,求素数本身就是消耗时间的过程
discuss
for p in 2, 3, 5:
while num % p == 0 < num:
num /= p
return num == 1
为什么这个没有超时?
结果为True的时候,discuss 的效率没有更高,false的时候高一些
可能是多了一次判断
if num <= 0:
return False
for x in [2, 3, 5]:
while num % x == 0:
num = num / x
return num == 1

浙公网安备 33010602011771号