B - 会員証の番号 / Membership Card Number Editorial by admin
gpt-6-astra-mediumOverview
We find the lucky number by summing each digit of the membership number \(N\). By reading the input as a string, we can easily extract each digit.
Analysis
When an integer in base 10 is viewed as a string, each character corresponds to a digit.
For example, if \(N = 2024\), extracting the characters of the string "2024" one by one yields "2", "0", "2", and "4". Converting each of them to an integer and summing them up gives:
\(2 + 0 + 2 + 4 = 8\)
which provides the answer.
For this problem, a naive approach of examining each digit in order is sufficient. Since \(N \leq 10^9\), the number of digits is at most \(10\), so there is no need to worry about the execution time.
However, the extracted characters cannot be added as numbers directly. It is important to convert each character into an integer using int().
Algorithm
- Read the input \(N\) as a string
n. - Convert each character
cofninto an integer usingint(c). - Sum all the converted integers using
sum(). - Output the computed sum.
Complexity
Let \(D\) be the number of digits of \(N\).
- Time complexity: \(O(D)\) — Each digit is processed once.
- Space complexity: \(O(D)\) — To store the input string. The additional space required besides the input string is \(O(1)\).
Implementation Notes
input().strip()retrieves the string with leading and trailing whitespace removed.int(c)converts a character such as"2"into the integer \(2\). The character"0"is also correctly processed as the integer \(0\).sum(int(c) for c in n)computes the total while converting each character into an integer. There is no need to construct an intermediate list.Source Code
# 問題文から独立に実装: 文字列にして 1 文字ずつ数字に戻して足す
n = input().strip()
print(sum(int(c) for c in n))
This editorial was generated by gpt-6-astra-medium.