Python 數位總和計算器

使用 Python 中的數學運算子計算整數中各個數字的總和。

在編輯器中嘗試

概述

計算數字總和涉及按順序提取數字的每個數字並累積值。

在 Python 中,這可以使用兩種主要技術來實現:使用模“% 10”和底除“// 10”的算術循環,或字串轉換迭代。

此算術方法在 O(log n) 時間和 O(1) 空間中運行,使其高效且與語言無關。

程式碼和執行輸出

具有絕對值的數字算術和函數支援負數。

sum_of_digits.py
在編輯器中嘗試
def sum_digits(n):
    n = abs(n)
    total = 0
    while n > 0:
        total += n % 10  # Extract last digit
        n //= 10         # Remove last digit
    return total

print("Sum of digits for 12345:", sum_digits(12345))
print("Sum of digits for 908:  ", sum_digits(908))
端子輸出
Sum of digits for 12345: 15
Sum of digits for 908:   17

逐步實施

  • 數學中的數字根計算
  • 校驗和驗證和雜湊演算法
  • 美學與數位命理學編碼難題

常見問題解答

這可以在 Python 中用一行完成嗎?

是的!您可以將數字轉換為字串,將每個字元轉換回整數,並對它們求和:`sum(int(d) for d in str(abs(n)))`。

相關主題