[英]sum digits (python simple)
我想編寫一個程序來添加數字直到它變成一個數字,這是我的代碼
n=int(input(""))
b=10**18
while not 1<=n<=b:
n=int(input(""))
else:
tot=0
while(n!=0):
dig=n%10
tot=tot+dig
n=n//10
s=0
if tot>=10:
while (tot!=0):
tot2=tot%10
s=s+tot2
tot=tot//10
else:
s=tot
print(s)
我認為它可以正常工作,但是當我輸入 88888888888 時,它給了我 16,因為 output 不是 7……但一切都是正確的……我該如何解決?
你可以簡單地做
s = n % 9
因為從數學中我們知道,任何數字的數字之和和一個數字本身在除以 9 時具有相同的余數。唯一的極端情況是當 n 可以被 9 整除時,在這種情況下,您需要 s=9。
最終代碼將是:
n=int(input())
b=10**18
while not 1 <= n <= b:
n=int(input())
if (n%9 == 0):
s = 9
else:
s = n % 9
你可以遞歸地處理這個問題。
def sumDigits(N): return N if N<10 else sumDigits(sum(divmod(N,10)))
sumDigits(88888888888) # 7
如果你想要一個數學解決方案:
def sumDigits(N): return (N+8)%9+1
問題很簡單,因為您沒有進行足夠的迭代,正如 Daniyar Aubekerov 評論的那樣,您需要 3 輪 88888888888 (88888888888->88->16->7 ) 但您只需要 2
解決它的一種方法是將公共部分分解為它們自己的函數並根據需要使用它們,例如
def digits(n):
"digits of the number n"
dig = []
while n>0:
n,d = divmod(n,10) # this do both n//10 and n%10
dig.append(d)
return dig
def sum_digits(n):
s = sum(digits(n)) #sum add together all the elements in the list
while s>10:
s = sum(digits(s))
return s
甚至更簡單,使用更直接的方法來獲取它,因為這也被稱為數字的數字根
def digital_root(n):
if n==0:
return 0
else:
return 1 + (n-1)%9
和一些快速測試
>>> digits(100)
[0, 0, 1]
>>> digits(88888888888)
[8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8]
>>> sum_digits(88888888888)
7
>>> digital_root(88888888888)
7
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.