PAT--1049. Counting Ones
2017-07-01 23:47
316 查看
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.
对于
个位:0~9的循环,即0123456789,一次循环只有1个1
十位:0~9的循环,每个数连续出现10次, 即000000000111111111….一次循环有10个1
百位:0~9的循环,每个数连续出现100次,….一次循环有100个1
…
规律性是很显然的。
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:
12Sample 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_JUDGE freopen("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; }
相关文章推荐
- 【PAT】1049. Counting Ones (30)
- ZJU PAT 1049 Counting Ones
- pat 1049. Counting Ones (30)
- PAT 解题报告 1049. Counting Ones (30)
- 【PAT甲级】1049. Counting Ones (30)
- PAT (Advanced Level) 1049. Counting Ones (30) 1到N中1出现的次数
- PAT 1049. Counting Ones (30)
- pat 1049 Counting Ones
- PAT 1049 Counting Ones
- PAT 1049 Counting Ones
- 【PAT】【Advanced Level】1049. Counting Ones (30)
- pat甲1049. Counting Ones (30)
- PAT (Advanced Level) Practise 1049 Counting Ones (30)
- 【PAT 1049】 Counting Ones 数学规律
- PAT甲级.1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)(计算1到N,这些数字中1出现的个数,before i after,归纳)
- pat 甲级 1049. Counting Ones (30)
- PAT 1049. Counting Ones
- pat 1049 Counting Ones