题目
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
思路
把数字用string保存,视作a[0]a[2]……a[n-1],考察每一位作为1可以有的数字个数,用M[i]记录。
设第i位为1,把左侧部分a[0]…a[i-1]视为一个数字A1,右侧部分a[i+1]…a[n-1]视作一个数字A2。
若a[i] < 1,M[i] = A1 * 10^(n-i-1)
若a[i] = 1,M[i] = A1 * 10^(n-i-1) + (A2+1)
若a[i] > 1,M[i] = (A1+1) * 10^(n-i-1)
下面考虑两端情况。
对于a[0](首位不能为0):
若a[0]=1,M[0] = A2+1
若a[0]>1,M[0] = 10^(n-1)
可见a[0]可以在A1=0时符合通用情况。
对于a[n-1]:
若a[n-1]<1,M[n-1] = A1
若a[n-1]=1,M[n-1] = A1 + 1
若a[n-1]>1,M[n-1] = A1 + 1
可见a[n-1]可以在A2=0时符合通用情况。
所以若A1或A2不存在就相应赋值为:A1=0,A2=a[n-1],可用以上通用公式求解。
(竟然用了3个小时…智商堪忧…一开始没有把a[i]=1的情况单独考虑,而是直接考虑了a[i]<=1,其实等于0和等于1时是不同的!)
柳神的代码是从最后一位开始计算,简洁了许多:
1049. Counting Ones (30)-PAT甲级真题(数学问题)
代码
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main(){
string a;
cin >> a;
int sum = 0;
int n = a.size();
for (int i=0; i<n; i++){
int A1 = i>0 ? stoi(a.substr(0, i)) : 0;
int A2 = i<n-1 ? stoi(a.substr(i+1, n-1-i)) : 0;
if (a[i]<'1'){
sum += (A1 * pow(10, n-i-1));
}
else if(a[i]=='1'){
sum += (A1 * pow(10, n-i-1) + A2 + 1);
}
else{
sum += ((A1+1) * pow(10, n-i-1));
}
}
cout << sum << endl;
return 0;
}