您的位置:首页 > 其它

求一个区间[a,b]中数字1出现的次数

2014-08-07 22:53 169 查看
原题见http://ac.jobdu.com/problem.php?pid=1373,如果【1,13】中出现1的整数有1,10,11,12,13 共6个

举个例子:

12105这个数字,千位上是2,那么千位上出现1的整数有多少个呢?1000~1999,11000~11999,总共是2x1000;(2 = 万位+1)

百位上是1,那么百位上出现1的整数有多少个呢?100~199,1100~1199...9100~9199,10100~10199,....11100~11199,12100~12105,总共是12x100+5+1;

十位上是0,那么十位上出现1的整数有多少个呢?10~19,110~119,210~219...1010~1019...10010~10019..12010~12019...总共:121x10

按照低位、当前位、高位来区分

求【1,N】中1出现的个数规律如下:

如果当前位小于1,那么个数等于高位*当前位率

如果当前位等于1,那么个数等于高位*当前位率 + 低位 + 1

如果当前位大于1,那么个数等于(高位+1)*当前位率

#include <iostream>
using namespace std;
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
#include <stack>
#include <set>

int getnum(int n,int i){
int res = 0;
int factor = 1;
while(n/factor){
int high = (n/factor)/10;
int curr = (n/factor)%10;
int low = n - (n/factor)*factor;
if(curr < i){
res = res + (high)*factor;
}else if(curr == i){
res = res + (high)*factor + low + 1;
}else if(curr > i){
res = res + (high+1)*factor;
}
factor = factor*10;
}
return res;
}

int main(){
int n;
int a,b;
//printf("%d",getnum(1,1));
while(scanf("%d%d",&a,&b) != EOF){
if(a > b)
swap(a,b);
if(a == 0)
a = 1;
printf("%d\n",getnum(b,1)-getnum(a-1,1));
}
///////////system("pause");
}





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐