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;
}

优解:

  1. #include <iostream>  
  2.   
  3. using namespace std;  
  4.   
  5. int main()  
  6. {  
  7.     int n, x, ans, v;  
  8.   
  9.     cin >> n >> x;  
  10.   
  11.     ans = 0;  
  12.     for(int i=1; i<=n; i++) {  
  13.         v = i;  
  14.         while(v) {  
  15.             if(v % 10 == x)  
  16.                 ans++;  
  17.             v /= 10;  
  18.         }  
  19.     }  
  20.   
  21.     cout << ans << endl;  
  22.   
  23.     return 0;  

优解2:(利用sprintf)

  1. #include<stdio.h>  
  2. #include<string.h>  
  3. #include<algorithm>  
  4. using namespace std;  
  5. int main()  
  6. {  
  7.     int n,x;  
  8.     scanf("%d%d",&n,&x);  
  9.     char map[1000001];  
  10.     int ans=0;  
  11.     for(int i=1;i<=n;i++)  
  12.     {  
  13.         sprintf(map+1,"%d",i);  
  14.         for(int j=1;map[j];j++)  
  15.         {  
  16.             if(map[j]==(x+48))  
  17.             {  
  18.                 ans++;  
  19.             }  
  20.         }  
  21.     }  
  22.     printf("%d ",ans);  
  23.     return 0;  
原文地址:https://www.cnblogs.com/ruoh3kou/p/7650439.html