1的数量
求区间[a,b]包含1的数量。例如区间[111,112], 整个区间包含两个数,分别为111,112,111包含3个1,而112包含2个1,所以区间[111,112]总共包含5个1
Input
多组测试数据。
每组测试数据包含两个整数a, b, 1 <= a <= b <= 10^18.
Output每组测试输出一行,表示1的数量,结果mod 10^9+7.
Sample Input
111 112 1 1000
Sample Output
5 301
#include <stdio.h> #include <string.h> #define LL long long const int M = 1000000000 + 7; LL d[25],a[25]; LL pow(int n) { LL s=1; while(n--) s*=10; return s; } void init() { d[0] = 0; //d[i]存储第i位前面有多少个1 for (int i = 1; i <= 18; i++) d[i] =pow(i-1)*i; } LL cal(LL x) { int cnt = 1; while (x) { a[cnt++] = x % 10;//将你得到的数字存起来. x /= 10; } LL ans = 0, temp = 0; for (int i = cnt - 1; i >= 1; i--) { ans += temp * pow( i - 1) * a[i];//表示记录前面已经访问了多少个1了, if (a[i] > 1) ans += (LL)a[i] * d[i - 1] + pow(i - 1);//当前位后面有多少个1 else if (a[i] == 1) { temp++;//当前位为1加1 ans += (LL )a[i] * d[i - 1]; } } ans = ans + temp; return ans; } int main() { LL a, b; init(); while (scanf("%lld%lld", &a, &b) != EOF) { printf("%lld\n", (cal(b) - cal(a - 1)) % M); } return 0; }