您的位置:首页 > 其它

PAT(甲级)1049

2015-09-26 10:19 302 查看


1049. Counting Ones (30)

时间限制

10 ms

内存限制

65536 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

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


#include <cstdio>
#include <cstring>
#include <cstdlib>

int Counting1(char *p);
int Count1ToN(int &n){
if(n<=0)
return 0;
char p[50];
sprintf(p,"%d",n);
int count=Counting1(p);
return count;
}

int Pow10(int n){
int base=10;
int res=1;
while(n){
if(n&0x1)
res *=base;
base *=base;
n >>=1;
}
return res;
}

int Counting1(char *p){
if(!p||*p<'0'||*p>'9')
return 0;
int first = *p-'0';
int length =strlen(p);
if(length==1){
if(first >=1)
return 1;
else
return 0;
}else{
int part1=0;
if(first >1)
part1=Pow10(length-1);
else if(first ==1)
part1=atoi(p+1)+1;
int part2=first*(length-1)*Pow10(length-2);
int remain=Counting1(p+1);
return part1+part2+remain;
}
}

int main()
{
int N;
scanf("%d",&N);
int count = Count1ToN(N);
printf("%d\n",count);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: