PAT 1049. Counting Ones (30)(计算1到N,这些数字中1出现的个数,before i after,归纳)
2016-09-09 04:50
423 查看
官网
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.输入描述:
Each input file contains one test case which gives the positive N (<=230).
输出描述:
For each test case, print the number of 1’s in one line.
输入例子:
12
输出例子:
5
题目大意
1.计算1到N,这些数字中1出现的个数。解题思路
1.分别计算每个位置上的1出现的个数再相加, 首先将原数字分为三部分,before+d+after,该位的数字为d,其前面的数字为before,后面为after,然后再对其进行分析,例如:2.分析任意一个三位数,求从0到该三位数的所有数字中十位上出现1的数字的个数:
例如对于222,则其百位+十位的组合只能是,01 11 21
百位和十位组合 | 实例222 |
---|---|
01 | 010 011 012 … 019 |
11 | 110 111 112 … 119 |
21 | 210 211 212 … 219 |
百位和十位组合 | 实例202 |
---|---|
01 | 010 011 012 … 019 |
11 | 110 111 112 … 119 |
百位和十位组合 | 实例212 |
---|---|
01 | 010 011 012 … 019 |
11 | 110 111 112 … 119 |
21 | 210 211 212 |
验证如下:
对于122,百位+十位有 01 11(即before=1+1,因为d=2>1,即可以把11这种组合的所有可能都取完),如下:
百位和十位组合 | 实例122 |
---|---|
01 | 010 011 012 … 019 |
11 | 110 111 112 … 119 |
百位和十位组合 | 实例102 |
---|---|
01 | 010 011 012 … 019 |
百位和十位组合 | 实例112 |
---|---|
01 | 010 011 012 … 019 |
11 | 110 111 112 |
每个位上出现1的次数与before有关,且至少有before*pow(10,w)个,这里w是after的位数。例如222,三位数,求的是十位上的数字为1的数字出现的次数,百位跟十位已经确定了有三种情况,这里after为1位数,即可以从0变化到9即有10种可能,例如百位+十位为01,则有010 011 … 019这十种可能。
每个位上出现1的次数还与该位上的数字d有关,如果d>1,则上述总结1还要加一种可能,即有(before+1)*pow(10,w)个。例如222:即如果202,至少可取01 11,例如222 d=2>1,还可以取21,且也可以把21后面的取完。
每个位上出现1的次数还与该位上的数字d有关,如果d=1,则有before*pow(10,w)+(after+1)个。例如222,212,202,百位+十位至少都可以取01 11,然后对于d=1,即212,还可以取210 211 212这三种情况。
代码解释
1.考虑每个位置上出现1的数字的个数,然后相加。2.求出每个位置的before,d,after。
3.按照上述总结的三种情况求每个位置上出现1的数字的个数。
代码
#include<iostream> #include<algorithm> using namespace std; int main() { int n; cin >> n; int after = 0,w=0,sum=0; while (true) { //求出每个位置的before,d,after(个位的after=0)。 if (n <= 0) break; int before = n / 10; int d = n % 10; //d>1的情况 sum += (before + ((d>1) ? 1 : 0))*pow(10, w); //d=1的情况 if (d == 1) sum += after+1; //下一轮的after和w after = d*pow(10, w) + after; w++; n = n / 10; } cout << sum << endl; return 0; }
相关文章推荐
- 1049. Counting Ones (30)【计算1 的个数】——PAT (Advanced Level) Practise
- PAT (Advanced Level) 1049. Counting Ones (30) 1到N中1出现的次数
- 1049. Counting Ones (30)计算个位数出现次数.
- 【PAT甲级】1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- pat 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)(数位dp(记忆化搜索))
- PAT 1049. Counting Ones (30)
- PAT甲级.1049. Counting Ones (30)
- pat 甲级 1049. Counting Ones (30)
- pat甲1049. Counting Ones (30)
- Python实现Pat 1049. Counting Ones (30)
- PAT (Advanced Level) Practise 1049 Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT_A 1049. Counting Ones (30)
- PAT 解题报告 1049. Counting Ones (30)
- 【PAT】【Advanced Level】1049. Counting Ones (30)
- PAT 甲级 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- pat 1049. Counting Ones (30)