您的位置:首页 > 其它

poj 3286 给定区间内0出现的次数

2016-05-24 10:58 453 查看
题意:给定一个区间[n,m],求这个区间内的整数中数字0出现的次数。如[10,21]为2,0在10和20中各出现一次。

思路:考虑每位上面0的个数。分类为这位为0或者不为0(如果是统计别的数字比如5出现的次数,那么还要考虑小于5的情况。leetcode上面有相应的问题)。

#include <cstdio>
#include <cstring>
using namespace std;
long long n,m;
long long f[15];
void init(){
f[0] = 1;
for(int i = 1;i<12;i++)
f[i] = 10*f[i-1];
}
long long solve(long long x){
if(x<0)
return 0;
long long tmp = x;
long long res = 1;
for(int i = 1;tmp>=10;i++){
long long a = x/f[i];
long long b = x%f[i-1];
int now = tmp%10;
tmp /= 10;
if(now)
res += a*f[i-1];
else
res += (a-1)*f[i-1] + b+1;
}
return res;
}
int main(){
init();
while(scanf("%lld %lld",&n,&m)){
if(n == -1 && m == -1)
break;
printf("%lld\n",solve(m)-solve(n-1));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: