Leetcode 264. Ugly Number II

时间:2022-11-02 13:16:15

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.

思路:如果num可以被2,3,5整除,那么就除以2,3,5.看最后是不是结果等于1.

class Solution:
# @param {integer} num
# @return {boolean}
def isUgly(self, num):
if num <= 0:
return False
for x in [2, 3, 5]:
while num % x == 0:
num /= x
return num == 1

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

 class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
res = [1]*n
p2 = 0
p3 = 0
p5 = 0 count = 1
while count < n:
cur = min(res[p2]*2, res[p3]*3, res[p5]*5)
if cur == res[p2]*2:
p2 += 1
elif cur == res[p3]*3:
p3 += 1
elif cur == res[p5]*5:
p5 += 1
if cur > res[count-1]:
res[count] = cur
count += 1
return res[-1]