The 10th Blue Bridge Cup java-c group-sum

1. Problem description:
Xiao Ming is very interested in the numbers containing 2, 0, 1, 9 in the digits. Such numbers from 1 to 40 include 1, 2, 9, 10 to 32, 39 and 40, a total of 28. Their sum is 574. May I ask, from 1 to 2019, what is the sum of all such numbers?
[Answer Submission]
This is a question that fills in the blanks with the result. You only need to calculate the result and submit it. The result of this question is an integer. When submitting the answer, only fill in this integer. If you fill in the extra content, you will not be able to score.

2. Thinking analysis:

Analyzing the question, we can know that we can loop in the range of 1-2019 to determine whether the current loop number contains numbers such as 2, 0, 1, and 9. Use a loop to divide by 10 to get the remainder of each position of the current traversed number If it exists, then accumulate the current traversed number, mainly to enumerate the entire process (you can first verify whether the sum of the numbers in the range of 1-40 is correct)

3. The code is as follows:

def solve(n: int):
    num = n
    # 依次获取当前数字各个位置上的数字
    while n > 0:
        t = n % 10
        if t == 2 or t == 0 or t == 1 or t == 9: return num
        n //= 10
    return 0


if __name__ == '__main__':
    res = 0
    for i in range(1, 2019):
        res += solve(i)
    print(res)

 

Guess you like

Origin blog.csdn.net/qq_39445165/article/details/114996485