Leetcode 263. 264. Ugly Number I and II

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.

 

 1 class Solution(object):
 2     def nthUglyNumber(self, n):
 3         """
 4         :type n: int
 5         :rtype: int
 6         """
 7         res = [1]*n
 8         p2 = 0
 9         p3 = 0
10         p5 = 0
11         
12         count = 1
13         while count < n:
14             cur = min(res[p2]*2, res[p3]*3, res[p5]*5)
15             if cur == res[p2]*2:
16                 p2 += 1
17             elif cur == res[p3]*3:
18                 p3 += 1
19             elif cur == res[p5]*5:
20                 p5 += 1
21             if cur > res[count-1]:
22                 res[count] = cur
23                 count += 1
24         return res[-1]
25                 

 

转载于:https://www.cnblogs.com/lettuan/p/6113513.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值