51Nod_1042 数字0-9的数量
http://www.51nod.com/Challenge/Problem.html#!#problemId=1042
题目
给出一段区间a-b,统计这个区间内0-9出现的次数。比如 10-19,1出现11次(10,11,12,13,14,15,16,17,18,19,其中11包括2个1),其余数字各出现1次。
输入
两个数a,b(1 <= a <= b <= 10^18)
输出
输出共10行,分别是0-9出现的次数
样例输入
10 19
样例输出
1
11
1
1
1
1
1
1
1
1
分析
此题是 51Nod_1009 数字1的数量 的扩展,求2~9出现的次数与求1出现的次数一样,只是0出现的次数有所不同,按照求1出现的次数求0出现的次数会发现计算多了,要减去高位出现0的情况,由于每次高位出现的数量要乘以i,因此就不是减去1,而是减去i,具体看程序。
C++程序
#include<iostream>
using namespace std;
typedef long long ll;
//计算区间[1,n]中数字x出现的个数
ll solve(ll n,int x)
{
//i表示当前为的权值,个位为1,十位为10... 。
//cur表示当前位的值,high表示cur之前的高位,low表示cur之后的低位
ll i=1,high=0,cur=0,low=0,num=0;
while(n/i)//遍历各个位
{
cur=(n/i)%10;//权值为i的位的值为cur
high=(n/i)/10;
low=n%i;
if(cur<x)//当前位的值小于x,权值为i的位为1的数的个数为high*i
num+=high*i;
else if(cur>x)//当前位的值大于x,权值为i的位为1的数的个数为(high+1)*i
num+=(high+1)*i;
else//当前位的值等于x,权值为i的位为1的数的个数为high*i+low+1
num+=high*i+low+1;
i*=10;
}
if(x==0)//如果x是0,就还要减去多加的
{
i=1;
while(n/i)
{
num-=i;
i=i*10;
}
}
return num;
}
int main()
{
ll a,b;
scanf("%lld%lld",&a,&b);
for(int x=0;x<10;x++)
printf("%lld\n",solve(b,x)-solve(a-1,x));
return 0;
}