leetcode 728 Self Dividing Numbers(自除數) python3 多種解法(巧用取餘和地板除,實現整數的位運算)

NO IMAGE
class Solution:
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
# method one  思路清晰,但是效率偏低的方法。多次的資料轉換,以及多餘操作
# res = []
# for i in range(left , right 1):
#     ss = str(i)
#     if '0' not in ss:
#         length = len(ss)
#         for j in range(length):              # 11,222 這樣自身元素重複的數是個坑, 容易出錯,還影響程式碼效率
#             if i % int(ss[j]) != 0:
#                 break
#             elif j == length - 1:     
#                 res.append(i)
# return res
# method two  在前面程式碼的基礎上,利用資料型別的轉換,減少一部分無用的除法操作
#         res = []
#         for i in range(left , right 1):
#             ss = set(str(i))
#             if '0' not in ss:
#                 ll = list(ss)
#                 for j in ll:              
#                     if i % int(j) != 0:
#                         break
#                     elif j == ll[-1]:     
#                         res.append(i)
#         return res
# method three   這個方法不用大量的資料型別轉換,但是仍有多餘的除法
res = []
for i in range(left,right 1):
k=i
flag=1
while k!=0:
val = k % 10
if val == 0 or i % val != 0:
flag=0
break
k//=10
if(flag==1):
res.append(i)
return res