洛谷OJP1980计数问题试计算在区间 1 到 n 的所有整数中,数字 x(0 ≤ x ≤ 9) 共出现了多少次?

题目描述

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

输入输出格式

输入格式:

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

输出格式:

1 个整数,表示 x 出现的次数。

输入输出样例

输入样例#1:

11 1

输出样例#1:

4

说明

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

AC代码(两种方法)

第一种(JAVA实现)

import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
        Scanner in=new Scanner(System.in);
        int n=in.nextInt();
        int x=in.nextInt();
        String strx=String.valueOf(x);
        char cx=strx.charAt(0);//将整数变换成字符
        int total=0;
        for(int i=1;i<=n;i++)
        {
            String str=String.valueOf(i);//将整数变换为字符串

            for(int j=0;j<str.length();j++)
            {
                if(str.charAt(j)==cx) total++; //遍历字符串中的每一个字符
            }
        }
        System.out.println(total);
    }

}

第二种方法(C++实现)

#include<iostream>
using namespace std;
int main()
{
    long long n,i,x,b,c,t=0;
    cin>>n>>x;//输入范围与要查的数字;
    for(i=1;i<=n;i++)//一到n进行循环;
    {
        b=i;//为了不改变i的值,就把i赋值给一个数;
        while(b!=0)//如果b不等于0,继续循环;
        {
            c=b%10;//求是否是x,是的话计数器加一;
            b=b/10;//求下一个数字是否为x;
            if(c==x) t++;计数器加一;
        }
    }
    cout<<t<<endl;//输出计数器的数字;
    return 0;//结束
}

猜你喜欢

转载自blog.csdn.net/qq_35694099/article/details/81146919