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:
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;
}
12Sample 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;
}
相关文章推荐
- 1049. Counting Ones (30)【计算1 的个数】——PAT (Advanced Level) Practise
- PAT甲级.1049. Counting Ones (30)
- PAT 解题报告 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT_A 1049. Counting Ones (30)
- 【PAT】1049. Counting Ones (30)
- PAT甲级 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- 【PAT (Advanced Level)】1049. Counting Ones (30)
- Python实现Pat 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)(计算1到N,这些数字中1出现的个数,before i after,归纳)
- pat 1049. Counting Ones (30)
- PAT (Advanced Level) Practise 1049 Counting Ones (30)
- PAT (Advanced Level) 1049. Counting Ones (30) 1到N中1出现的次数
- PAT 甲级 1049. Counting Ones (30)
- PAT (Advanced Level) 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- pat 甲级 1049. Counting Ones (30)
- 【PAT甲级】1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)