計算1至n中數字x出現的次數

題目:計算1至n中數字x出現的次數

直接炒栗子!

如果x=[1,9]

2059 5
個位:205個10,2051+1205*1+1:[1,2050)+[2050, 2059] 個位9>5
十位:20個100,2010+(9+1)20*10+(9+1):[1,2000)+[2000,2059] 十位5=5
百位:2個1000,21002*100:[1,2000)+[2000, 2059] 百位0<5
千位:0個10000,00:[10000,2059] 千位2<5

如果x=0

2059 0
個位:205個10,(2051)1+1(205-1)*1+1:[1,2050)+[2050, 2059] 個位9>0
十位:20個100,(201)10+10(20-1)*10+10:[1,2000)+[2000,2059]
百位:2個1000,(21)100+(59+1)(2-1)*100+(59+1):[1,2000)+[2000, 2059] 百位0=0
千位:不考慮

爲什麼"-1",拿個位舉例。[1,2050)從[1,10]到[2041,2050),一共有205個長度爲10的區間,但是最後一個區間不包括2050啊,不包括0~

窩好菜……想了好久哦……0的愣就是想不明白???www

#include <iostream>
#include <cstdio>
using namespace std;

int Count(int n, int x)
{
    int ans = 0;
    int tmp = n;
    int base = 1;
    if(x == 0)
    {
        while(tmp >= 10)
        {
            if(tmp % 10 == x)
                ans += (tmp / 10 - 1) * base + n % base + 1;
            else
                ans += (tmp / 10 - 1) * base + base;
            base *= 10;
            tmp /= 10;
        }
        return ans;
    }
    while(tmp)
    {
        if(tmp % 10 < x)
            ans += tmp / 10 * base;
        else if(tmp % 10 == x)
            ans += tmp / 10 * base + n % base + 1;
        else if(tmp % 10 > x)
            ans += tmp / 10 * base + base;
        base *= 10;
        tmp /= 10;
    }
    return ans;
}

int main()
{
    int n, x;
    while(cin >> n >> x)
        cout << Count(n, x) << endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章