PAT B1117 數(shù)字之王

我剛開始以為數(shù)字至少需要處理一次,原來初始數(shù)字全部小于10的時候,可以不處理。代碼有點(diǎn)繁瑣,先記錄一下,后續(xù)優(yōu)化代碼。

#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
struct Node {
    int data;
    bool still;//是否發(fā)生了變化
};
int cube(int a) {
    if (a == 0)
        return 0;
    int total = 1;
    while (a) {
        total *= pow(a % 10, 3);
        a = a / 10;
    }
    int ans = 0;
    while (total) {
        ans += (total % 10);
        total = total / 10;
    }
    return ans;
}
int main() {
    int hashCnt[10] = {0};
    int n1, n2;
    cin >> n1 >> n2;
    bool flag = false;//是否全部變成了一位數(shù)
    vector<Node> list;
    for (int i = n1; i <= n2; i++) {
        Node node;
        node.data = i;
        node.still = false;
        list.push_back(node);
    }
    if(n2<10) flag = true;
    while (flag == false) {
        flag = true;
        for (auto it = list.begin(); it != list.end(); it++) {
            if ((*it).still == true) {
                continue;
            }
            int temp = cube((*it).data);
            if (temp >= 10) {
                flag = false;
            }

            if (temp == (*it).data) {
                (*it).still = true;
            }
            else {
                (*it).data = temp;
            }
        }
    }

    for (auto it = list.begin(); it != list.end(); it++) {
        hashCnt[(*it).data]++;
    }
    int max = -1;
    for (int i = 0; i < 10; i++) {
        if (max < hashCnt[i]) {
            max = hashCnt[i];
        }
    }
    int cnt = 0;
    for (int i = 0; i < 10; i++) {
        if (hashCnt[i] == max) {
            cnt++;
        }
    }
    cout << max << endl;
    for (int i = 0; i < 10; i++) {
        if (hashCnt[i] == max) {
            cout << i;
            if (cnt-->1) {
                cout << " ";
            }
        }
    }
    return 0;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容