Problema
Add up every decimal digit of n. For 352 the digits are 3, 5 and 2.
Implement sum_of_digits(n).
Input
n: A positive integer.
Output
Return the sum of its digits.
Vincoli
1 ≤ n ≤ 10¹⁸
Esempi
Esempio 1
Input:
n = 352
Output atteso:
expected = 10
Input:
long long n = 352;
Output atteso:
long long expected = 10;
Input:
long n = 352;
Output atteso:
long expected = 10;
Spiegazione
3 + 5 + 2 = 10.
Esempio 2
Input:
n = 1000
Output atteso:
expected = 1
Input:
long long n = 1000;
Output atteso:
long long expected = 1;
Input:
long n = 1000;
Output atteso:
long expected = 1;
Spiegazione
1 + 0 + 0 + 0 = 1.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
Each step only needs the current last digit and the remaining prefix.
Suggerimento 2
Repeatedly peel off digits with division and remainder, or iterate through a string representation.
Suggerimento 3
Make sure single-digit inputs return that digit unchanged.
Complessità attesa
O(d) time, O(1) extra space