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 (≤2^30).
Output Specification:
For each test case, print the number of 1’s in one line.
Sample Input:
12
Sample Output:
5
这题的主要利用数学的方式,用暴力法的话有两个测试点会超时。
数学思路我是参考这个老哥的博客,我觉得解释得详细。这里主要是想自己写一遍,要是以后想起来可以回来看看。
计算小于等于 n 的非负整数中数字 1 出现的个数:
我们可以算出每一位上出现1的个数,然后累加起来。
根据每一位上值的不同,可分为三种情况:
(1)值为0
(2)值为1
(3)2~9
为解决这个问题设立三个变量high,low,now。
high–高位值
low–低位值
now–当前位的值,用来判断是哪种情况
举个具体的列子:
1237056
第一种情况,
0在百位上,我们统计百位上1的个数,
#include <iostream>
using namespace std;
int N;
int main() {
cin >> N;
int sum = 0;
for (int i = 1; i <= N; i *= 10) {//这里是i<=N,没有等号的话会出错
int low = N % i;
int temp = N / i;
int high = temp / 10;
int now = temp % 10;
if (now == 0)
sum += high * i;
else if (now == 1)
sum += high * i + 1 * (low + 1);
else
sum += (high + 1) * i;
if (high == 0)
break;
}
cout << sum;
}