簡體   English   中英

在數字中添加數字(需要代碼說明)

[英]Adding Digits in a Number (Need Code Explanation)

我在其他地方遇到過此代碼段。 它只是將所有數字加到給定的數字中:

def sumDigits(n):
    sum = 0
    while n > 0:
        sum += n % 10
        n //= 10
    return sum

問題是,我根本沒有邏輯。 特別是,我不完全了解循環的作用:

   while n > 0:
        sum += n % 10  # Why n % 10?
        n //= 10       # Again, not sure why we divide the number by 10

有人可以向我提供該算法如何工作的示例嗎?

謝謝!

您應該了解兩件事:

  1. n % 10為您提供數字的最右邊數字。 例如: 123 % 10 = 3
  2. n // 10刪除數字的最右邊數字。 例如: 123 // 10 = 12

因此,如果重復該過程,您將獲得所需的結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM