1~n 之间 数字x出现的次数

声明: 仅个人小记

暴力法

/*
    输入: n 整数, 0 =< x <= 9
    输出: 1~n 中 数字x出现的次数
*/
#include <iostream>
#include <ctime> 

using namespace std;

int main(void)
{
    clock_t startTime, endTime;


    int n, x;
    cin >> n >> x;
    startTime = clock();
    int t;
    int cnt = 0;

    for (int i = 1; i <= n; i ++) {
        t = i;
        while (t) {
            if (t%10 == x) cnt ++;
            t /= 10;
        }
    }   
    endTime = clock();
    cout << cnt << endl;

    cout << "time elpased: " << double(endTime-startTime) *1000 /CLOCKS_PER_SEC << "ms" << endl;
    cout << endTime-startTime << endl;
    return 0;
}

优化

/*
    效率极大提升,算法耗费时间仅仅和给定的整数的长度有关
*/
#include <iostream>
#include <ctime>
using namespace std;

int main(void)
{
    int n, x;

    cin >> n >> x;
    int startTime, endTime;
    startTime = clock();
    int t;
    int cnt = 0;
    int k = 1;
    int a;
    int b = n;
    while (b) {
        a = b % 10;
        b = b / 10;

        cnt += b * k;

        if (a > x) cnt += k;
        else if (a == x) cnt += (n%k+1);

        k *= 10;
    }


    if (x == 0) { // x == 0 时,不一样的地方是 我们都知道 01 02 03 不算是两位数, 001 002 003 不算是三位数, 所以减去 (100+10) 
        cnt --;// 因为起点是 1 不是 0, 所以个位上的0 少了一个 
        int p = 10;
        int q = 0;
        while (n/10) {
            q += p;
            p *= 10;
            n/=1;
        }
        cnt -= q;
    }

    endTime = clock();
    cout << cnt << endl;
    cout << "time elpased : " << (double)(startTime-endTime)*1000/CLOCKS_PER_SEC << "ms"<<endl;
    return 0;
}

时间花费对比

这里写图片描述0;
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值