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
题意:给定n,求1~n之间出现2的次数
思路:
- 枚举1~n之间每一个数的每一位(数据量大了肯定超时)
- 特殊做法:先求出n的位数k,然后循环k次,依次求出1~k位(从右到左)中每一位出现2的次数,加起来即可,复杂度O(k)分析当前位
一、n != 0时:
- 如果当前位比n小,那么当前位取n时,左边只能取[0, left - 1],一共left个数,右边可以取a个数,组合就是乘法,left * a
- 如果当前位等于n,那么左边是[0,left - 1]时,右边可以取a个;左边是left时,右边[0, right],所以有left * a + right + 1
- 如果当前位大于n,那么左边可以[0, left],共left + 1个,右边a个,组合是(left + 1) * a
二、n == 0时:(如果要让当前位取0,那么左边的数不能为0,只能从1开始)
- 如果当前位等于0,那么左边是[1,left - 1]时,右边可以取a个;左边是left时,右边[0, right],所以有(left-1) * a + right + 1
- 如果当前位大于0,那么左边可以[1, left],共left 个,右边a个,组合是left * a
这里给定一般做法,[L, R]区间内出现n的次数,对于本题令L = 1, n = 2即可
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 20;
const int INF = 0x3fffffff;
typedef long long ll;
int get_num(int k, int n) { //该函数实现[1, k]出现n的次数
int a = 1, ans = 0;
while (k / a) {
int left = k / (a * 10); //当前位左边的数值
int now = (k / a) % 10; //当前位的数字
int right = k % a; //当前位右边的数值
if(n) //n !=0 时
if (now < n) ans += left * a;
else if (now == n) ans += left * a + 1 + right;
else ans += (left + 1) * a;
else //n == 0时
if (now) ans += left * a;
else ans += (left - 1) * a + right + 1;
a *= 10;
}
return ans;
}
int main() {
int L, R, n;
cin >> L >> R;
cout << get_num(R, n) - get_num(L - 1, n) << endl;
return 0;
}
//再次提醒:上述代码给出的是一般做法,本题的话,需要令L = 1,n = 2