PAT (Advanced Level) 1049. Counting Ones (30) 1到N中1出现的次数

来源:互联网 发布:java 挂起当前线程 编辑:程序博客网 时间:2024/05/21 09:14

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
题目的时间限制是10ms,若用遍历的方法检测从1到n每个数中1的个数,在n较大时肯定会超时。
对于n的每一位,可以分为该位为0,该位为1,和该位大于1三种情况讨论。
考虑n=15042的百位,由于百位是0,1到n中百位能否为1仅由更高的两位15决定,这两位可以是00到14,即001XX、011XX...141XX,低位XX可以是00到99,故满足条件的共15*100=1500个数。
考虑n=15142的百位,由于百位是1,在上例15042的基础上,低位42贡献了151XX,XX可以是00到42,共43个数,故满足条件的有15*100+42+1=1543个数。
考虑n=15242的百位,由于百位大于1,在第一个例子15042的基础上,增添了151XX,XX可以是00到99,故满足条件的有(15+1)*100=1600个数。
对于n的每一位,都可以通过分析该位数字,以及高位和低位数字,来得到从1到n中该位出现1的次数。
/*2015.7.26cyq*/#include <iostream>using namespace std;int main(){int n;cin>>n;int cur,low,high;int count=0;int base=1;while(n/base){low=n%base;//低位cur=n/base%10;//当前位high=n/base/10;//高位switch(cur){case 0:count+=high*base;break;case 1:count+=high*base+low+1;break;default:count+=(high+1)*base;break;}base*=10;}cout<<count<<endl;return 0;}


0 0