PAT-A 1049. Counting Ones
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
思路参考:
http://blog.csdn.net/tiantangrenjian/article/details/19908885
程序代码:
#include<stdio.h>
#include<math.h>
#include<string.h>
char c[11]={0};
int count_1(int n);
int main()
{
int n,i=0;
scanf("%d",&n);
int sum = count(n);
printf("%d",sum);
return 0;
}
int count(int n)
{
int factor = 1;
int sum = 0,lower,high,cur;
while(n/factor!=0)
{
lower = n%(factor);
high = n/(factor*10);
cur = (n/factor)%10;
switch(cur)
{
case 0:
sum += high *factor;
break;
case 1:
sum += high *factor + lower+1;
break;
default:
sum += (high+1)*factor;
break;
}
factor=factor*10;
}
return sum;
}