1049. Counting Ones (30)

Posted 给杰瑞一块奶酪~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1049. Counting Ones (30)相关的知识,希望对你有一定的参考价值。

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


如果穷举的话太麻烦了,还要排着计算每个数有几个1。可以假定某一位是1,看一下此时有多少个数满足不超过n,假如32105这个数,假定十位是1,他的高位是321,低位是5,高位肯定不能是321(32110 > 32105),当高位取0-320时,低位可以取0-9,此时是(320 + 1)* 10。接洗下来假设百位是1,百位本来就是1,高位为32,低位为05,高位可以取0-32,高位取0-31时,低位可以取0-9,高位取32时,低位只可以取0-5,所以此时是32 * 100 + 5 + 1。继续假设千位是1,高位和低位都可以尽情取所在范围内的数,即高位取0-3,低位可以取0-999,结果很清楚了已经(3+1)*1000。可见只需要分所假设位是0,1,和其他的情况即可。
代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <set>
#include <cstring>
using namespace std;

int main()
{
    int n;
    cin>>n;
    int base = 1;
    int low,now,high;
    int ans = 0;
    while(n/base)
    {
        high = n / (base * 10);
        now = (n / base) % 10;
        low = n % base;
        if(now == 0)//now 位 要是1 则high必然要减小1
        ans += high * base;
        else if(now == 1)//now位本来就是1 则high位不变
        ans += high * base + low + 1;
        else//那么low可以取base个
        ans += (high + 1) * base;
        base *= 10;
    }
    cout<<ans;
}

 

以上是关于1049. Counting Ones (30)的主要内容,如果未能解决你的问题,请参考以下文章

PAT 1049 Counting Ones (30)

A1049 Counting Ones (30分)

PAT (Advanced Level) Practice 1049 Counting Ones (30 分)

PAT Advanced 1049 Counting Ones (30) [数学问题-简单数学问题]

1049 Counting Ones (30 分)难度: 难 / 知识点: 分治 / DP

PAT 1049 Counting Ones [难]