[NOIP2013]记数问题

链接:[NOIP2013]记数问题

题号:NC16538
时间限制:C/C++/Rust/Pascal 1秒,其他语言2秒
空间限制:C/C++/Rust/Pascal 128 M,其他语言256 M
64bit IO Format: %lld

题目描述

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

11 1

输出

复制4

4

备注:

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

方法一:

#include<bits/stdc++.h>
using namespace std;

int main(){
    int n,x;
    cin>>n>>x;
    int count=0;
    for(int i=1;i<=n;i++){
        int tmp=i;
        while(tmp>0){
            int a=tmp%10;
            if(a==x){
                count++;
            }
            tmp/=10;
        }
    }
    cout<<count;
    return 0;
}

方法二:

#include<bits/stdc++.h>
using namespace std;

int main(){
    int n,x;
    cin>>n>>x;
    int count=0;
    for(int i=1;i<=n;i++){
        string s=to_string(i);
        for(int j=0;j<s.size();j++){
            if(s[j]-'0'==x){
                count++;
            }
        }
    }
    cout<<count;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值