程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Sword finger offer python:45 Ugly number

編輯:Python

subject : To include only qualitative factors 2、3 and 5 The number of is called ugly (Ugly Number). for example 6、8 All ugly numbers , but 14 No , Because it contains quality factors 7. It's customary for us to 1 As the first ugly number . Seek the order from small to large N Ugly number .

analysis : Keep separately *2、*3、*5 The minimum position of , Number of times with this position *2、3、5 Compare separately , that will do .

Code :

class Solution:
def func(self , n):
if n == 0:
return 0
res = []
n2 , n3 , n5 = 0,0,0
for i in range(n):
if i == 0:
res.append(1)
else:
r2 , r3 , r5 = res[n2]*2 , res[n3]*3 , res[n5]*5
to_add = min(r2 , r3 , r5)
res.append(to_add)
if r2 == to_add:
n2 += 1
if r3 == to_add:
n3 += 1
if r5 == to_add:
n5 += 1
return res
a = 10
s = Solution()
print(s.func(a))

Output :

[1, 2, 3, 4, 5, 6, 8, 9, 10, 12]


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved