我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC
我的PAT-ADVANCED代码仓:https://github.com/617076674/PAT-ADVANCED
原题链接:
PAT-BASIC1019:https://pintia.cn/problem-sets/994805260223102976/problems/994805302786899968
PAT-ADVANCED1069:https://pintia.cn/problem-sets/994805342720868352/problems/994805400954585088
题目描述:
PAT-BASIC1019:
PAT-ADVANCED1069:
知识点:字符串
思路:迭代求解,一旦得到数字6174或XXXX型的数字,break跳出循环
本题需要注意的一点是对于“0010”这样的数据,在字符串和数字转换的过程中,不可以忽略前面的“0”。
时间复杂度根据数据的不同而变化很大,不好计算。空间复杂度是O(1)。
C++代码:
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
bool compareNum(int num1, int num2);
int noRisingArray(int num);
int noDownArray(int num);
int main() {
int num;
cin >> num;
while (true) {
int num1 = noRisingArray(num);
int num2 = noDownArray(num);
num = num1 - num2;
if (num == 6174) {
printf("%04d - %04d = %04d\n", num1, num2, num);
break;
} else {
if (num1 == num2) {
printf("%04d - %04d = 0000", num1, num2);
break;
} else {
printf("%04d - %04d = %04d\n", num1, num2, num);
}
}
}
}
bool compareNum(int num1, int num2) {
if (num1 <= num2) {
return false;
} else {
return true;
}
}
int noRisingArray(int num) {
vector<int> nums;
while (num > 0) {
nums.push_back(num % 10);
num /= 10;
}
while (nums.size() < 4) {
nums.push_back(0);
}
sort(nums.begin(), nums.end(), compareNum);
int result = 0;
for (int i = 0; i < nums.size(); i++) {
result = result * 10 + nums[i];
}
return result;
}
int noDownArray(int num) {
vector<int> nums;
while (num > 0) {
nums.push_back(num % 10);
num /= 10;
}
while (nums.size() < 4) {
nums.push_back(0);
}
sort(nums.begin(), nums.end());
int result = 0;
for (int i = 0; i < nums.size(); i++) {
result = result * 10 + nums[i];
}
return result;
}
C++解题报告:
来源:CSDN
作者:清風逐尘乀
链接:https://blog.csdn.net/qq_41231926/article/details/83215688