vijos P1848 记数问题
自答【119ms内存456.0 KiB】
#include<iostream>
using namespace std;
int num = 0;
void judge(int n, int x) {
int t = n % 10;
if (n != 0 || t != 0)
if (x == t || x == n)
{
num++;
t = n / 10;
judge(t, x);
}
else
{
t = n / 10;
judge(t, x);
}
}
int main()
{
int n, x;
cin >> n >> x;
for (int i = 1; i <= n; i++)
{
judge(i, x);
}
cout << num;
return 0;
}
优解:
- #include <iostream>
- using namespace std;
- int main()
- {
- int n, x, ans, v;
- cin >> n >> x;
- ans = 0;
- for(int i=1; i<=n; i++) {
- v = i;
- while(v) {
- if(v % 10 == x)
- ans++;
- v /= 10;
- }
- }
- cout << ans << endl;
- return 0;
- }
优解2:(利用sprintf)
- #include<stdio.h>
- #include<string.h>
- #include<algorithm>
- using namespace std;
- int main()
- {
- int n,x;
- scanf("%d%d",&n,&x);
- char map[1000001];
- int ans=0;
- for(int i=1;i<=n;i++)
- {
- sprintf(map+1,"%d",i);
- for(int j=1;map[j];j++)
- {
- if(map[j]==(x+48))
- {
- ans++;
- }
- }
- }
- printf("%d\n",ans);
- return 0;
- }