算法提高 计数问题

问题描述
  试计算在区间 1 到 n 的所有整数中,数字 x(0 ≤ x ≤ 9)共出现了多少次?例如,在 111 中,即在 1234567891011 中,数字 1 出现了 4 次。
输入格式
  输入文件名为 count.in。
  输入共 1 行,包含 2 个整数 n、x,之间用一个空格隔开。
输出格式
  输出文件名为 count.out。
  输出共 1 行,包含一个整数,表示 x 出现的次数。

输入输出样例
count.in
count.out
11 1
4

解题思路:使用while循环,通过取余将每一个位进行比较即可。

t=temp%10;
temp=temp/10;
#include<stdio.h>
int main() {
    
    
	int x,n,i,count=0,temp=0;
	scanf("%d%d",&n,&x);
	for(i=1;i<=n;i++){
    
    
		int t=0;
		temp=i;
		while(temp){
    
    
			t=temp%10;
			if(t==x){
    
    
				count++;
			}
			temp=temp/10;
		}
		
	} 
	printf("%d",count);
	return 0;
}

运行结果:

11 1
4
--------------------------------
Process exited after 2.102 seconds with return value 0
请按任意键继续. . .

1到11中数字1出现了4次。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/mjh1667002013/article/details/115037787