1069 The Black Hole of Numbers (20分)
程序员文章站
2022-07-16 08:03:16
...
用string完成
比较麻烦,要将string
转为数组再进行排序,然后再转化为string
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
bool cmp(int a, int b) {
return a > b;
}
int getVal(vector<int> s) {
int res = 0;
for (int i = 0; i < s.size(); i++) {
res *= 10;
res += s[i];
}
return res;
}
vector<int> getArray(string s) {
while (s.length() < 4) {
s += '0';
}
vector<int> res;
for (int i = 0; i < 4; i++) {
res.push_back(s[i] - '0');
}
return res;
}
int main() {
string s;
cin >> s;
while (true) {
vector<int> array = getArray(s);
sort(array.begin(), array.end());
int inc = getVal(array);
sort(array.begin(), array.end(), cmp);
int desc = getVal(array), res = desc - inc;
printf("%04d - %04d = %04d\n", desc, inc, res);
if (res == 6174 || res == 0) {
return 0;
}
s = to_string(res);
}
}
利用c风格字符串
注意c风格字符串的常用函数(strlen)、c风格字符串转数字(atoi或sscanf)、数字转c风格字符串(sprintf)的函数。
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
bool cmp(char a, char b) {
return a > b;
}
int main() {
char s[5];
scanf("%s", s);
while (true) {
while (strlen(s) < 4) {
s[strlen(s)] = '0';
}
sort(s, s + 4);
int inc = atoi(s);
sort(s, s + 4, cmp);
int desc = atoi(s), res = desc - inc;
printf("%04d - %04d = %04d\n", desc, inc, res);
if (res == 6174 || res == 0) {
return 0;
}
sprintf(s, "%d", res);
}
}
坑点
给出的数字不一定是四位数字,要自行补0。
上一篇: 一维数组与二维数组
下一篇: java如何将String转换为enum
推荐阅读
-
1069 The Black Hole of Numbers (20分)
-
1069 The Black Hole of Numbers (20 分)(模拟)
-
【PAT】A1069 The Black Hole of Numbers (20分)
-
PAT(A)1069 The Black Hole of Numbers (20分)
-
pat-1069 The Black Hole of Numbers (20分)
-
[PAT-A 1069]The Black Hole of Numbers
-
PAT-A-1069 The Black Hole of Numbers 【验证】
-
PAT A1069 The Black Hole of Numbers (20分)