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的所有数字里面出现1的个数
题解:第一种方法是,扫每一位,然后把每一位按是不是1来考虑,很好很实用
#include <iostream>
using namespace std;
int main() {
int n, left = 0, right = 0, a = 1, now = 1, ans = 0;
scanf("%d", &n);
while(n / a) {
left = n / (a * 10), now = n / a % 10, right = n % a;
if(now == 0) ans += left * a;
else if(now == 1) ans += left * a + right + 1;
else ans += (left + 1) * a;
a = a * 10;
}
printf("%d", ans);
return 0;
}
第二种颇有些数位dp的意思,找转移方程,反正我有些佩服,不过但凡是dp都会,有空间上的消耗
#include<iostream>
#include<vector>
using namespace std;
int main(){
long long int n,sum=0;
cin>>n;
int a[n+1]={0};
//vector<int> a(n+1,0);
for(int i=1;i<=n;i++){
if(i%10==0)
a[i]=a[i/10];
else if(i%10==1)
a[i]=a[i-1]+1;
else if(i%10==2)
a[i]=a[i-1]-1;
else
a[i]=a[i-1];
sum+=a[i];
}
cout<<sum<<endl;
return 0;
}