PAT Top 1018 Subnumber 题解

Given a positive integer N, let us define a subnumber of N as a consecutive number of digits NOT starting with 0. For example if N=1021, it has 7 subnumbers, namely, 1, 10, 102, 1021, 2, 21 and 1 (again). Here is your task: please calculate the sum of all the subnumbers of N. For 1021, the sum is 1+10+102+1021+2+21+1 = 1158. Since the result may be very large, output the answer modulo 1000000007 (10​9​​+7) please.

Input Specification:

Each input file contains one test case, which gives the integer N (0<N<10​100000​​) in a line.

Output Specification:

Print in a line the sum of all N's subnumbers (modulo 1000000007).

 

 

对于M位的整数d_0d_1d_2d_3 \dots d_{M-1}d_j左边包括它自己在内有g_j位的非零数字,d_j对最后结果的贡献为

contribution(d_j)=(g_j \times d_j\times \sum_{i=0}^{M-j-1}10^i)\%(10^9+7).

最后的结果就是

result=(\sum_{i=0}^{M-1}contribution(d_i)) \% (10^9+7).

提前以递推的形式计算10的若干次方有助于降低计算复杂度。代码如下。

#include <iostream>
#include <vector>
#include <string>

using namespace std;
const long long N = 1e9 + 7;


int main()
{
    string input;
    cin >> input;

    vector<long long> residual(input.size(), 0);
    residual[0] = 1;
    for(size_t i = 1; i < residual.size(); i++){
        residual[i] = (residual[i - 1] * 10 + 1) % N;
    }

    long long result = 0;
    int g = 0;
    for(size_t i = 0; i < input.size(); i++){
        long long n = input[i] - '0';
        if(n) g += 1;
        int k = input.size() - i;
        result += (g * n * residual[k - 1]);
        result %= N;
    }
    cout << result;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值