我刚开始以为数字至少需要处理一次,原来初始数字全部小于10的时候,可以不处理。代码有点繁琐,先记录一下,后续优化代码。
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
struct Node {
int data;
bool still;//是否发生了变化
};
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;//是否全部变成了一位数
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;
}