http://www.codeforces.com/problemset/problem/552/B
题意:给你一个数N,问你从1到N所有的数的数字位数之和为多少。
解法:
不难看出,数对应的数字位数分别为:
1-9 1
10-99 2
100-999 3
……
可以得到,如果给你的数是一个N位数,那么所有N-1位的数字位数之和是可以计算的。
例如:
1-9 9 * 1
10-99 90 * 2
100-999 900 * 3
……
而N位数的计算公式为(N=len)
(a - Pow[len - 1] + 1) * len
累加完就是答案。
#include <bits/stdc++.h>
#define _ ios_base::sync_with_stdio(0);cin.tie(0);
#define INF 0x3f3f3f3f
#define eps 1e-6
typedef long long LL;
const double pi = acos(-1.0);
const long long mod = 1e9 + 2015;
using namespace std;
char s[105];
LL num[15];
LL Pow[15];
int main()
{
ios_base::sync_with_stdio(false); cin.tie(0);
//freopen("int.txt","r",stdin);
//freopen("out.txt","w",stdout);
num[1] = 9;
for(int i = 2;i <= 12;i++)
num[i] = num[i - 1] * 10;
Pow[0] = 1;
for(int i = 1;i <= 12;i++)
Pow[i] = Pow[i - 1] * 10;
cin >> s;
LL len = strlen(s);
LL a = 0;
for(LL i = 0;i < len;i++)
{
a += (s[i] - '0');
if(i != len - 1)
a *= 10;
}
//cout << a << endl;
LL ans = 0;
for(LL i = 1;i < len;i++)
ans += num[i] * i;
//cout << ans << endl;
//cout << (a - Pow[len - 1] + 1) * len << endl;
ans += (a - Pow[len - 1] + 1) * len;
cout << ans << endl;
return 0;
}
PS:自带的pow()函数好像有点问题
在计算
ans += (a - Pow(10,len - 1) + 1) * len;
的时候貌似len会减1。。。不是很懂