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

原题见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");
}





  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值