1049 Counting Ones (30分)

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 (≤).

Output Specification:

For each test case, print the number of 1's in one line.

Sample Input:

12

Sample Output:

5

题目分析:一道数学题 题目据说是《编程之美》上的一道题
具体的推法好像很麻烦的样子 之后有时间会看看
 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <climits>
 3 #include<iostream>
 4 #include<vector>
 5 #include<queue>
 6 #include<map>
 7 #include<set>
 8 #include<stack>
 9 #include<algorithm>
10 #include<string>
11 #include<cmath>
12 using namespace std;
13 
14 int main()
15 {
16     int N;
17     cin >> N;
18     int count = 0,left=0,right=0,now=1,a=1;
19     while (N/a)
20     {
21         left = N / (a * 10);
22         now = N / a % 10;
23         right = N % a;
24         if (now == 0)count += left * a;
25         else if (now ==1)count += left * a + right + 1;
26         else if (now > 1)count += (left + 1) * a;
27         a *= 10;
28     }
29     cout << count;
30 }
View Code

猜你喜欢

转载自www.cnblogs.com/57one/p/12044478.html