一百万的数位和
Digit Sum of One Million
题目详情
计算从 1 到 1,000,000(含)所有整数的各位数字之和。例如,46 的数位和是 10。
Calculate the sum of the digits from 1 to 1 million, inclusive? For example, the sum of the digits of 46 is 10.
解析
把从 0 到 999,999 的所有数都看成带前导零的 6 位数。这样一共有 个数。
对任意一个数位位置来说,数字 都恰好各出现 100,000 次,因此该位置对总数位和的贡献是
一共有 6 个数位,所以从 0 到 999,999 的总数位和为
题目要的是从 1 到 1,000,000(含),因此只需再加上 的数位和 ,而数字 0 的数位和是 0,不影响结果。
所以答案是
Original Explanation
It’s often easier to count digit contributions.
Every integer from 0 to 999,999 is a 6-digit string if we allow leading zeros. So in that range we have exactly numbers, each with 6 digits.
Each of the 6 positions (hundreds of thousands, ten-thousands, …, ones) cycles evenly through 0-9.
-
In each position, each digit 0,1,…,9 appears exactly 100,000 times (since 1,000,000 / 10 = 100,000).
-
So the total contribution of that digit position to the digit sum is:
-
With 6 digit positions, the grand total from 0 to 999,999 is
We want 1 to 1,000,000 not 0 to 999,999
- If we take the sum from 0 to 999,999 we get 27,000,000
- Add the digit sum of 1,000,000 which is 1.
- Remove the digit sum of 0, which is 0.
So the final answer is: