求从0到n一共有多少个1

1049. Counting Ones (30)

时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

The task is simple: given any positive integer N, you are supposed to count the total number of 1's in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1's in 1, 10, 11, and 12.

Input Specification:

Each input file contains one test case which gives the positive N (<=230).

Output Specification:

For each test case, print the number of 1's in one line.

Sample Input:
12
Sample Output:
5

这个题目是很有趣的,让我想了很久,在网上找了几个答案,结果没一个有像样的注释,看不懂,只能自己花了一个小时想出来了。

从0到1000输出一遍是很有必要的,有助于我们快速找到规律。我们可以很轻松的看到,100对应答案21,1000对应答案301,10000对应答案4001.....

也就是说,除了1最高位为1,每增加10^x次方答案增加的数目是恒定的xi。

递归处理第一位,比如第一位数字是a,那么我们先考虑a00000以前的所有,再递归加上a右边的位数就是答案了。

#include <iostream>
#include <vector>

using namespace std;

int w[]={0,0,1,20,300,4000,50000,600000,7000000,80000000,900000000};
//每10加1,每100加20,每1000加300.......
void init(){//这个是验算用的
    int sum = 0;
for(int i = 0 ;i<2;i++)
        for(int j = 0;j<10;j++)
        //for(int k=0;k<10;k++)
            for(int l=0;l<10;l++){
            if(i==1)    sum++;
            if(j==1)    sum++;
            //if(k==1)    sum++;
            if(l==1)    sum++;
            cout<<i<<j<<l<<" "<<sum<<endl;
        }
}
int pow(int t){
    int l = 1;
    while(t--)
        l=l*10;
    return l;
}

int f(int n){
    if(n==0)
        return 0;
    if(n<10)
        return 1;
    int wei=0;  //有多少位
    int m = n;
    while(m)
    {
        wei++;
        m/=10;
    }
    int no = pow(wei-1);    //当前位的最小值
    int asdasd=n/no;          //n是不是1开头的啊
    if(asdasd==1){
        int t = n%no;
        return w[wei]+t+1+f(t);
        //比如 1234就要300 + 234 + 1,这个234+1表示从1000到1234一共有235个千位1,f(t)求百位以后的数
    }
    else
    {   //若是asdasd第一位比1大
        int t = n%no;
        return w[wei]*(asdasd)+no+f(t);
    }

}

int main()
{
   //init();
    int n;
    cin>>n;
    cout<<f(n)<<endl;
    return 0;
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值