计数问题 C C++ Python Java Go

目录

题目描述

思路分析

C

C++

Python

Python超级NB霹雳无敌封神版本

Java

Go


题目描述

试计算在区间 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

思路分析

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

具体操作就是:两个循环,外循环实现从1到n的所有整数,内循环实现每一个整数的各位上的数字比对,采用和10取余的方式取出它的各位,一次和10取余可以取出个位上的数字,之后让其除以10,就可以把十位上的数字拉到各位,如此反复直到它为0.

要注意Python中的 / 不只是整除,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)

Python超级NB霹雳无敌封神版本

n,x=map(int,input().split())
print(str([i for i in range(n+1)]).count(str(x)))

详情解释请看 计数问题 两行代码解决 Python_^o^叶子^0^的博客-CSDN博客

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

Go

package main

import "fmt"

func main() {
	temp, i, m, n, count := 0, 0, 0, 0, 0
	fmt.Scanf("%d%d", &m, &n)
	for i = 1; i <= m; i++ {
		temp = i
		for temp > 0 {
			if n == temp%10 {
				count++
			}
			temp /= 10
		}
	}
	fmt.Println(count)
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MaolinYe(叶茂林)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值