PAT A 1049 Counting Ones

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 (<=2^30^).

Output Specification:

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

Sample Input:

12

Sample Output:

5

这完全是一道找规律的数学题。。。好难找。。

#include <cstdio>
int main() {
    int n, a = 1, ans = 0;
    int left, now, right;//这里left指的是高位(左边一位)的数字,now指的是当前位的数字,right指的是右边的数(所有低位一起表示的数)。
    scanf("%d",&n);
    while(n/a != 0) {
        left = n / (a * 10);
        now = n / a % 10;
        right = n % a;
        if(now == 0) ans += left * a;//真的佩服算法笔记的思路
        else if(now == 1) ans += left * a + right + 1;
        else ans += (left + 1) * a;
        a *= 10;
    }
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/joah_ge/article/details/81057611