B - 会員証の番号 / Membership Card Number Editorial by admin
swe-2-highExplanation
Problem Summary
Given a positive integer \(N\), compute the sum of its decimal digits (the “lucky number”).
Approach
The simplest method is to read \(N\) as a string and convert each character to its numeric value, summing them. The integer value of a digit character '0' through '9' is obtained by subtracting '0' from its character code.
Alternatively, read \(N\) as an integer and repeatedly extract the last digit via \(N \bmod 10\), then remove it via \(N \leftarrow \lfloor N / 10 \rfloor\).
Pseudocode
sum ← 0
for each character c in N:
sum ← sum + (c - '0')
print sum
Proof of Correctness
Let the decimal representation of \(N\) be \(d_k d_{k-1} \cdots d_1 d_0\) (each \(d_i\) is a digit between \(0\) and \(9\)). The required answer is \(S = \sum_{i=0}^{k} d_i\).
String method: When the input is read as a string, the \(i\)-th character corresponds exactly to digit \(d_i\). The expression c - '0' yields the integer value of digit c, so the loop adds each \(d_i\) exactly once. Hence the final sum equals \(S\).
Modulo method: \(N \bmod 10\) equals the last digit \(d_0\), and \(\lfloor N / 10 \rfloor\) is \(N\) with its last digit removed. Each iteration adds the current last digit and then removes it, so every digit is added exactly once before \(N\) becomes \(0\). The total therefore equals \(S\).
Either way, the output matches the definition of the lucky number.
Complexity
Since \(N \leq 10^9\), there are at most \(10\) digits.
- Time: \(O(\log_{10} N)\), effectively constant
- Space: \(O(\log_{10} N)\) for the input itself when read as a string; otherwise \(O(1)\) auxiliary space
Implementation Notes
- \(N\) fits in a 32-bit integer, but processing it as a string avoids worrying about magnitude limits entirely.
- There is no tie-breaking in this problem; the answer is uniquely determined.