您的位置:首页 > 其它

PAT 1049. Counting Ones (30)

2018-03-26 20:39 369 查看
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 <iostream>
using namespace std;
int CountOnes(int n)
{
int count = 0;
int factor = 1;
int higher,lower,cur;
while(n / factor != 0)
{
higher = n / (factor * 10);
lower = n - (n / factor) * factor;
cur = (n / factor) % 10;
switch(cur)
{
case 0:
count += higher * factor;
break;
case 1:
count += higher * factor + lower + 1;
break;
default:
count += (higher + 1) * factor;
}
factor *= 10;
}
return count;
}
int main()
{
int n;
cin>>n;
cout<<CountOnes(n)<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PAT