算法1 直接计数
由于a,b的大小都不大,所以可以直接枚举每个数的每一位,如果是2,就答案ans++
C++ 代码
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int ans,r;
int main()
{
int a,b;
cin>>a>>b;
for(int i=a;i<=b;i++)
{
int t=i;
while(t)
{
r=t%10;
t/=10;
if(r==2) ans++;
}
}
cout<<ans;
return 0;
}
算法2 数位Dp
C++ 代码
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 10;
int get(vector<int> num, int l, int r)
{
int res = 0;
for (int i = l; i >= r; i -- ) res = res * 10 + num[i];
return res;
}
int power10(int x)
{
int res = 1;
while (x -- ) res *= 10;
return res;
}
int count(int n, int x)
{
if (!n) return 0;
vector<int> num;
while (n)
{
num.push_back(n % 10);
n /= 10;
}
n = num.size();
int res = 0;
for (int i = n - 1 - !x; i >= 0; i -- )
{
if (i < n - 1)
{
res += get(num, n - 1, i + 1) * power10(i);
if (!x) res -= power10(i);
}
if (num[i] == x) res += get(num, i - 1, 0) + 1;
else if (num[i] > x) res += power10(i);
}
return res;
}
int main()
{
int a,b;
cin>>a>>b;
cout << count(b, 2) - count(a - 1, 2) << ' ';
return 0;
}