PAT(甲级)1049

来源:互联网 发布:java 写html文件 编辑:程序博客网 时间:2024/06/07 11:07

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;}

0 0
原创粉丝点击