2013 junior T1 计数问题 题解

题目描述

试计算在区间 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%的数据,
1≤ n ≤ 1,000,000,0 ≤ x ≤ 9

解题思路

暴力
这道题最多是7,000,000次计算,只要从一开始一个数一个数地分解就可以了。

代码

#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
    int a,b,count=0,ans;
    cin>>a>>b;
    for(int i=1;i<=a;i++){
        int j=i;
        while(j!=0){
            if(j%10==b){
                count++;
            }
            j/=10
        }
    }
    ans=count;
    cout<<ans;
    return 0;
}

本来我是没有解题思路的。。。

猜你喜欢

转载自blog.csdn.net/johnwayne0317/article/details/84324567