1049. Counting Ones (30) (搜索)

1049. Counting Ones (30)

时间限制
10 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

题意:给定一个数n,求1-n中,所有数字中出现的1的个数

题解:一开始, 我是搜索做的源码如下.


#include 

int search(int x) {
    if (x == 0) return 0;
    if (x < 10) return 1;
    int cnt = 1, tmp = x;
    while (tmp >= 10) {
        tmp /= 10;
        cnt *= 10;
    }

    if (tmp == 1)
        return (x - cnt + 1) + search(cnt - 1) + search(x - cnt);
    else
        return cnt + tmp * search(cnt - 1) + search(x - tmp * cnt);
}

int main() {
    int n;
    scanf("%d", &n);
    printf("%d\n", search(n));

    return 0;
}


网上看了看别人的, 又是另一种做法, 非常简洁!


#include 

int solve(int n) {
    int cnt = 0, factor = 1;
    while (n >= factor) {
        int high = n / (factor * 10);
        int low = n - n / factor * factor;
        if ((n / factor) % 10 == 0) cnt += high * factor; 
        else if ((n / factor) % 10 == 1) cnt += high * factor + low + 1;
        else cnt += high * factor + factor;
        factor *= 10;
    }
    return cnt;
}

int main() {
    int n;
    scanf("%d", &n);
    printf("%d\n", solve(n));

    return 0;
}




你可能感兴趣的:(搜索,PATA)