Đề bài
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.
Ràng buộc
1 ≤ n ≤ 10¹⁸
Ví dụ
Ví dụ 1
Đầu vào:
n = 352
Kết quả mong đợi:
expected = 10
Đầu vào:
long long n = 352;
Kết quả mong đợi:
long long expected = 10;
Đầu vào:
long n = 352;
Kết quả mong đợi:
long expected = 10;
Giải thích
3 + 5 + 2 = 10.
Ví dụ 2
Đầu vào:
n = 1000
Kết quả mong đợi:
expected = 1
Đầu vào:
long long n = 1000;
Kết quả mong đợi:
long long expected = 1;
Đầu vào:
long n = 1000;
Kết quả mong đợi:
long expected = 1;
Giải thích
1 + 0 + 0 + 0 = 1.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Each step only needs the current last digit and the remaining prefix.
Gợi ý 2
Repeatedly peel off digits with division and remainder, or iterate through a string representation.
Gợi ý 3
Make sure single-digit inputs return that digit unchanged.
Độ phức tạp mong đợi
O(d) time, O(1) extra space