3 回答

TA貢獻1865條經驗 獲得超7個贊
你可以把它變成一個字符串,然后分解它。例如:
number = 11
[int(c) for c in str(number)]
或者你可以用整數除法和模數的數學方式來做:
number // 10, number % 10
這兩個都給你一個兩個 1 的序列。
如果我了解您要正確執行的操作,則可以嘗試以下操作:
sum(n//10 + n%10 for n in range(1, sums + 1))
當是 12 時給出 51。sums如果你想接受更多的數字,你還必須添加n // 100etc。

TA貢獻1809條經驗 獲得超8個贊
number = int(input("Please input a number: "))
sum = 0
counter = 0 # will count from 1-9, and reset if it goes too far
for n in range(number):
if counter > 9:
counter = 1 # limit the counter
sum += counter
這將計數到您輸入的數字,它將存儲由計數器管理的 1-9 序列的總和。

TA貢獻2036條經驗 獲得超8個贊
希望這是您正在尋找的,
sums = int(input("Enter page sum: ")) #Get the input
lst=map(str,list(range(1,sums+1))) #Map int list to string
lst_concat = ''.join(lst) #Merging the elements in the list together
lst2=list(lst_concat) #Make it into a list again
sum(map(int,lst2)) #Sum the elements of the digit
添加回答
舉報