P1980 计数问题 AC于2018.6.7 https://www.luogu.org/problemnew/show/P1980

题目描述

试计算在区间 11 到 nn 的所有整数中,数字 x(0 ≤ x ≤ 9)x(0≤x≤9) 共出现了多少次?例如,在 11 到 1111 中,即在 1,2,3,4,5,6,7,8,9,10,111,2,3,4,5,6,7,8,9,10,11 中,数字 11 出现了 44 次。

输入输出格式

输入格式:

22 个整数 n,xn,x ,之间用一个空格隔开。

输出格式:

11 个整数,表示 xx 出现的次数。

输入输出样例

输入样例#1: 

11 1

输出样例#1: 

4

说明

对于 100\%100% 的数据, 1≤ n ≤ 1,000,000,0 ≤ x ≤ 91≤n≤1,000,000,0≤x≤9 。

循环写法

#include <cstdio>
using namespace std;
int main()
{
	int m,n,i,j,s=0;
	scanf("%d%d",&m,&n);
	for(i=1;i<=m;i++)
	{
		j=i;
		while(j)
		{
			if(j%10==n)
			s++;
			j=j/10;
		}
	}
	printf("%d",s);
	return 0;
}

递归写法

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int snvi(int m,int a)
{
	int n,l=0;
	if(m>0)
	{
		n=m;
		while(n)
		{
			if(n%10==a)
			l++;
			n/=10;
		}
		return l+snvi(m-1,a);
	}
	else
	return 0;
}

int main()
{
	int m,n;
	scanf("%d%d",&m,&n);
	printf("%d",snvi(m,n));
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41100192/article/details/81209780
今日推荐