题目:1019 数字黑洞 - PAT (Basic Level) Practice (中文) (pintia.cn)
字符串读入
#include<bits/stdc++.h>
using namespace std;
string s1,s2;
int main()
{
cin>>s1;
while(1)
{
sort(s1.begin(),s1.end());
s2=s1;
reverse(s2.begin(),s2.end());
if(s1==s2)
{
printf("%04d - %04d = 0000\n",stoi(s1),stoi(s2));
}
if(stoi(s2)-stoi(s1)==6174)
{
printf("%04d - %04d = 6174\n",stoi(s2),stoi(s1));
break;
}
printf("%04d - %04d = %04d\n",stoi(s2),stoi(s1),stoi(s2)-stoi(s1));
s1=to_string(stoi(s2)-stoi(s1));
}
return 0;
}
可能是由于大量使用stoi()产生拷贝导致的运行超时,进行预处理一下,发现没有什么卵用:
#include<bits/stdc++.h>
using namespace std;
string s1,s2;
int main()
{
cin>>s1;
while(1)
{
sort(s1.begin(),s1.end());
s2=s1;
reverse(s2.begin(),s2.end());
int temp1=stoi(s1),temp2=stoi(s2); //预处理
if(temp1==temp2)
{
printf("%04d - %04d = 0000\n",temp1,temp2);
}
if(temp2-temp1==6174)
{
printf("%04d - %04d = 6174\n",temp2,temp1);
break;
}
printf("%04d - %04d = %04d\n",temp2,temp1,temp2-temp1);
s1=to_string(temp2-temp1);
}
return 0;
}
其实原因在于给定的数值N是0到1e4之间的数值,也就是有可能给定的不是一个四位数,比如9,
我们只是在输出格式上加了前导0,实际上并没有用,我们应该在字符串本身加上前导0:
加完之后:
还有一个没过的原因是当N - N = 0000
的时候也应该结束程序,但是我没有break,加上就可以了:
#include<bits/stdc++.h>
using namespace std;
string s1,s2;
int main()
{
cin>>s1;
while(1)
{
while(s1.size()<4)s1="0"+s1;
sort(s1.begin(),s1.end());
s2=s1;
while(s2.size()<4)s2="0"+s2;
reverse(s2.begin(),s2.end());
int temp1=stoi(s1),temp2=stoi(s2);
if(temp1==temp2)
{
printf("%04d - %04d = 0000\n",temp2,temp1);
break;
}
if(temp2-temp1==6174)
{
printf("%04d - %04d = 6174\n",temp2,temp1);
break;
}
printf("%04d - %04d = %04d\n",temp2,temp1,temp2-temp1);
s1=to_string(temp2-temp1);
}
return 0;
}
整数读入
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int>v;
vector<int>v2;
int A = 0, B = 0, C = 0;
void sovel(int x)
{
while (1)
{
while (x)
{
v.push_back(x % 10);
x /= 10;
}
while (v.size() < 4)
{
v.push_back(0); // 补齐为4位数
}
sort(v.begin(), v.end(), greater<int>());
A = v[0];
for (int i = 1; i < v.size(); i++)
{
A = A * 10 + v[i];
}
v2 = v;
sort(v2.begin(), v2.end());
B = v2[0];
for (int i = 1; i < v2.size(); i++)
{
B = B * 10 + v2[i];
}
if (v[0] == v[1] && v[1] == v[2] && v[2] == v[3] || (v2[0] == v2[1] && v2[1] == v2[2] && v2[2] == v2[3]))
{
printf("%d - %d = 0000\n", A, B);
break;
}
if(A-B==6174)
{
printf("%04d - %04d = 6174\n",A,B);
break;
}
C = A - B;
printf("%04d - %04d = %04d\n", A, B, C);
v.clear();
v2.clear();
x=C;
}
}
int main()
{
int x = 0; cin >> x;
sovel(x);
return 0;
}