[英]Algorithm to sum up all digits of a number
你能向我解釋一下這個循環是如何工作的嗎? 第一次循環之后和第二次循環之后發生了什么等等。
def sum(n):
s = 0
while n:
s += n % 10
n /= 10
return s
>>> print sum(123)
6
所以基本上,我們在這個算法中所做的是我們一次從數字的最低有效數字中取出一位數字並將其添加到我們的 s(總和變量)中,一旦我們添加了最低有效數字,然后我們將其刪除並一遍又一遍地執行上述操作,直到數字仍然為零,那么我們如何知道最低有效數字,只需將 n 除以 10 取余數,現在我們如何刪除最后一位(最低有效位),我們只是將它除以 10,所以你去吧,如果它不明白,請告訴我。
def sum(n):
s = 0
while n:
s += n % 10
n /= 10
return s
最好這樣重寫(更容易理解):
def sum(n):
s = 0 // start with s = 0
while n > 0: // while our number is bigger than 0
s += n % 10 // add the last digit to s, for example 54%10 = 4
n /= 10 // integer division = just removing last digit, for example 54/10 = 5
return s // return the result
Python 中的n > 0
可以簡單地寫成n
但我認為這對初學者來說是不好的做法
int main()
{
int t;
cin>>t;
cout<<floor(log10(t)+1);
return 0;
}
輸出
254
3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.