PAT--1049. Counting Ones

来源:互联网 发布:Cisco网络排错 编辑:程序博客网 时间:2024/06/06 02:56

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~n这n个数,要知道数字1出现的次数,可以计算出个位、十位、百位…这些数位上1出现的次数,累加起来即可。
个位:0~9的循环,即0123456789,一次循环只有1个1
十位:0~9的循环,每个数连续出现10次, 即000000000111111111….一次循环有10个1
百位:0~9的循环,每个数连续出现100次,….一次循环有100个1

规律性是很显然的。

#include <bits/stdc++.h>using namespace std;int n, sum;int length(int n){    int ret = 0;    while(n){        ret++;        n /= 10;    }    return ret;}int main(){#ifndef ONLINE_JUDGEfreopen("data.in", "r", stdin);#endif    cin >> n;    n++;    int k = 10;    int len = length(n);    for(int i = 1; i < len; ++i){        int a = (n / k * (k / 10));        int b = (n % k > k / 10) ? (n % k < 2 * k / 10 ? (n % k - k / 10) % (k / 10) : k / 10) : 0;        //cout << "a + b: " << a + b << endl;        //cout << "b: " << b << endl;        sum += a + b;        k *= 10;    }    // 处理最高位    int p = n / ((int)pow(10, len - 1));    if(p == 1) sum += n % (int)pow(10, len - 1);    else sum += pow(10, len - 1);    cout << sum << endl;    return 0;}