PAT Counting Ones (30)
来源:互联网 发布:老鼠爱大米 知乎 编辑:程序博客网 时间:2023/12/10 21:15
题目
题目描述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出现的个数再相加, 首先将原数字分为三部分,before+d+after,该位的数字为d,其前面的数字为before,后面为after,然后再对其进行分析,例如:
2.分析任意一个三位数,求从0到该三位数的所有数字中十位上出现1的数字的个数:
- 例如对于222,则其百位+十位的组合只能是,01 11 21
2. 对于202 则其百位+十位的组合只能是,01 11 ,对比可以发现该位上的数字d为0,所以不能取到21,即与该位上的数字是否大于等于1有关。
3.例如对于212,则其百位+十位的组合只能是,01 11 21,且21 后面只能有三种可能,如下:
把上述三者结合可以发现,假如before=2,那么后面百位+十位的组合至少都有俩种,即01 11(即不超过21就行),什么时候有三种组合呢,即如果d>1,如222,d=2>1,那么百位+十位就有三种情况,且可以把21取完,即包括210 211 212 … 219,有十种情况,而当d=1,如212,此时也有三种情况,但21这种情况不能取完,只能取 210 211 212 三种(after=2,可以从0取到2,有after+1种情况)。
- 验证如下:
对于122,百位+十位有 01 11(即before=1+1,因为d=2>1,即可以把11这种组合的所有可能都取完),如下:
对于102,则只有 01 这种可能(d<1,不能取到11),即:
对于112,有01 11俩种情况,但11不能取完(d=1),且只能取110 111 112(即after+1=3,3种情况),即:
总结为:
每个位上出现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;}
- PAT Counting Ones (30)
- 1049. Counting Ones (30)-PAT
- pat 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- 【PAT】1049. Counting Ones (30)
- PAT-A1049. Counting Ones (30)
- PAT.1049. Counting Ones (30)
- pat-a1049. Counting Ones (30)
- PAT A1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT A 1049. Counting Ones (30)
- 【PAT (Advanced Level)】1049. Counting Ones (30)
- 【PAT甲级】1049. Counting Ones (30)
- 1049. Counting Ones (30) PAT甲级
- PAT甲级.1049. Counting Ones (30)
- PAT甲级练习1049. Counting Ones (30)
- Redis3.0集群方案分析
- 《我的RobotFramework书》1-2 测试用例, Test Case
- Retrofit
- Eclipse Mars 如何安装svn
- [转自人人]DSP面经
- PAT Counting Ones (30)
- Iterator递归迭代实例。剪切文件并删除文件夹
- 1101计算表达式
- bzoj1864(树形dp)
- 关于自卑,与君共勉
- 跳坑指南-smb服务器配置
- windows环境下安装npm、cnpm、bower
- studio 设置代码快捷键
- js闭包理解