丑数系列
目录
丑数系列
1.丑数
题目:
https://leetcode-cn.com/problems/ugly-number/
思路:
就是让这个数字不断地除以2.3.5 如果最后变成了1 就说明是个丑数
代码:
class Solution:
def isUgly(self, num: int) -> bool:
if num<=-231 or num>=231-1:
return False
while num >1:
if num %2 == 0:
=int(num/2)
numelif num %3 ==0:
=int(num/3)
num elif num %5 ==0:
=int(num/5)
numelse:
break
if num == 1:
return True
else:
return False
丑数II
题目:
https://leetcode-cn.com/problems/ugly-number-ii/
思路:
利用三指针,维护i2 i3 i5三个指针分别指向2 3 5
代码:
class Solution:
def nthUglyNumber(self, n: int) -> int:
= [1] # 先初始化为1
res = i3 = i5 = 0 # 初始化为0
i2 for i in range(1,n):
= min(res[i2]*2,res[i3]*3,res[i5]*5) # 从小到大找
mins
res.append(mins)if res[i] == res[i2]*2:
+= 1
i2 if res[i] == res[i3]*3:
+= 1
i3 if res[i] == res[i5]*5:
+= 1
i5 return res[n-1]