Compute sum of digits in all num

作者: 黑山老水 | 来源:发表于2018-04-11 08:40 被阅读3次

Description:

Compute sum of digits in all numbers from 1 to n

Example:

Input: n = 5
Output: Sum of digits in numbers from 1 to 5 = 15

Input: n = 12
Output: Sum of digits in numbers from 1 to 12 = 51

Input: n = 328
Output: Sum of digits in numbers from 1 to 328 = 3241

Link:

https://www.geeksforgeeks.org/count-sum-of-digits-in-numbers-from-1-to-n/

解题方法:

除了暴力破解以外,还有一种更快的解法:
以328为例:

  • 首先算百位的数:
    3会出现29次(从300到329)
    1会出现100次(从100到199)
    2会出现100次(从200到299)
  • 然后算10位的数:
  1. 同上一样在数字大于300的时候:
    1会出现10次(从310到319)
    2会出现9次(从320到329)
  2. 在数字小于300的时候:
    10位上的数字会出现3次1-9的变化(10 - 99, 110 - 199, 210 - 299)
    每变化一次,10位上的数都会出现10次(比如从10变为20:10 11 12 13 14 15 16 17 18 19)
    所以在数字小于300时候,10位数字总和为 3 * (1 + 2 + .. + 9) * 10 = 3 * 45 * 10

Time Complexity:

O(n) n为给定的数有多少位

完整代码:

int sumOfDigits(int n) {
    vector<int> sums(10, 0);
    int sum = 0;
    for(int i = 0; i <= 9; i++) {
        sum += i;
        sums[i] = sum;
    }
    sum = 0;
    int temp = 10;
    while(temp <= n) {
        temp *= 10;
    }
    temp /= 10;
    while(temp > 0) {
        last *= 10;
        sum += sums[(n / temp) % 10 - 1] * temp + (n / temp) % 10 * (n % temp + 1);
        sum += last * 45 * temp / 10;
        last = n / temp;
        temp /= 10;
    }
    return sum;
}

相关文章

网友评论

    本文标题:Compute sum of digits in all num

    本文链接:https://www.haomeiwen.com/subject/cszohftx.html