计数问题 C C++ Python Java

目录

题目描述

思路分析

C

C++

Python

Java


题目描述

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

输入输出格式

输入格式:

输入共 1 行,包含 2 个整数 n、x,之间用一个空格隔开。

输出格式:

输出共 1 行,包含一个整数,表示 x 出现的次数。

输入输出样例

输入样例#1: 

11 1

输出样例#1: 

4

思路分析

对于每一个数,我们首先将它按位数划分出来,提取它的各个位数,一一比对就行。

要注意Python中的 / 不只是整除。

C

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

C++

#include <iostream> 
using namespace std;
int main() {
	int temp,i,m,n,count=0;
	cin>>m>>n;
	for(i=1;i<=m;i++){
		temp=i;
		while(temp){
			if(n==temp%10)
			count++;
			temp/=10;
		}	
	}
	cout<<count<<endl;
}

Python

m,n=map(int,input().split())
count=0
for i in range(1,m+1):
    temp=i
    while temp:
        if temp%10==n:
            count=count+1
        temp=int(temp/10)
print(count)

Java

import java.util.Scanner;
public class studying {
    public static void main(String[] args) {
        int temp,i,n,m,count=0;
        Scanner scan=new Scanner(System.in);
        m=scan.nextInt();
        n=scan.nextInt();
        for(i=1;i<=m;i++){
            temp=i;
            while(temp>0){
                if(temp%10==n)
                    count++;
                temp/=10;
            }
        }
        System.out.println(count);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_62264287/article/details/125964789