题目描述如下: 题目大致意思: 输入一个四位数字,先从大到小排序得到a,再从小到大排序得到b;让a-b得到一个新的数,重复上面的过程,直到得到6174或者0为止。 提交结果: 测试用例未能全部通过,放在第二轮刷题时解决。 提交的代码如下:
#include<iostream> #include<string> #include<algorithm> #include<iomanip> using namespace std; int func1(int n); int func2(int n); bool cmp(char c1, char c2) { return c1 > c2; } int main() { int n; cin >> n; int temp1 = func1(n); int temp2 = func2(n); while (true) { int temp = temp1 - temp2; if (temp != 0 && temp != 6174) { cout <<setfill('0')<<setw(4)<< temp1 << " - " << setfill('0') << setw(4) << temp2 << " = " << setfill('0') << setw(4) << temp << endl; temp1 = func1(temp); temp2 = func2(temp); } else { if (temp == 0) { cout << setfill('0') << setw(4) << temp1 << " - " << setfill('0') << setw(4) << temp2 << " = " << "0000" << endl; break; } if (temp == 6174) { cout << setfill('0') << setw(4) << temp1 << " - " << setfill('0') << setw(4) << temp2 << " = " << setfill('0') << setw(4) << temp << endl; break; } } } } int func1(int n) { string str = to_string(n); sort(str.begin(), str.end(), cmp); return atoi(str.c_str()); } int func2(int n) { string str = to_string(n); sort(str.begin(), str.end()); return atoi(str.c_str()); }本次提交后累计得分840。
