1018 Subnumbers (35 分)(C++)

PAT顶级题解目录​​​​​​​

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).

Sample Input:

1234567890123456789

Sample Output:

332876913

题目大意:给出一个很大的数字字符串(可能有100000位),计算它的子数组字符串(非0开头)的数字和的大小,注意结果对1000000007取模。

解题思路:

我用1024来举例

1开头:1,10,102,1024,可以发现结果和为1*1111,0*111,2*11,4*1

0开头:0,02,024,可以发现结果和为0*111,2*11,4*1(不过这个不合要求)

2开头:2,24,可以发现结果和为2*11,4*1

4开头:4,可以发现结果和为4*1

总结规律,先不考虑0的问题,,设字符串的总长度为L,位于第i位的数字num(从左往右数,从0开始计数),对结果的贡献为 num * (i+1)* 1...1(L-i个1),但是本题并没有将每个数字单独分开看,因为如果出现0,则其后的数字计算的次数都要受影响。也就是并一定出现i+1次。

考虑设一个tempans,记录目前遍历到的数字

tempans = 4 , ans = 4

tampans=24, ans = 4+24

tempans = 024, ans=4+24

tempans = 1024, ans= 4+24+1024

代码:

#include <bits/stdc++.h>
using namespace std;
long long int mod = 1000000007;
int main(){
	string s;
	cin >> s;
	reverse(s.begin(), s.end());
	int len = s.length();
	long long int ans = 0, tempans = 0;
	vector<long long int> v(len);
	v[0] = 1;
	for(int i = 1; i < len; ++ i)
		v[i] = (v[i-1] * 10 + 1) % mod;
	for(int i = 0; i < len; ++ i){
		tempans += (s[i] - '0') * v[i];
		if(s[i] != '0')
			ans = (ans + tempans) % mod;
	} 
	printf("%lld", ans);
} 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章