Pat(Advanced Level)Practice--1049(Counting Ones)

来源:互联网 发布:python中的单例模式 编辑:程序博客网 时间:2024/06/08 09:43

Pat1049代码

题目描述:

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

AC代码:
#include<cstdio>using namespace std;int CountOneNum(int n){int ret=0;int factor=1;int low=0;int cur=0;int high=0;while(n/factor!=0){low=n-(n/factor)*factor;cur=(n/factor)%10;high=n/(factor*10);switch (cur){case 0:ret+=high*factor;break;case 1:ret+=high*factor+low+1;break;default:ret+=(high+1)*factor;break;}factor*=10;}return ret;}int main(int argc,char *argv[]){int n;scanf("%d",&n);printf("%d\n",CountOneNum(n));return 0;}

更详细的分析,请看博客链接:http://blog.csdn.net/cstopcoder/article/details/22760793
0 0
原创粉丝点击