@[toc]目录
(一)问题描述
问题来源:https://www.nowcoder.com/pat/6/problem/4045 转载自牛客网
通读题意后我们可以提出一下问题:
1、如何将4位整数的各位取出并对其进行排序。
2、如果4位数字中有多个0,例如输入3,顺序是3000,逆序是0003,如何满足输出格式?
(二)问题解析
1、对于各位数字的取出,我们可以采用n%10;n/10;这样一种方式从低位到高位取出数字,对于4位数字从低到高的排序,仿照算出一串整数中最大三位的思路,边取数字边比较,这里给出参考题目链接:https://blog.csdn.net/D1352612146/article/details/95051261
该参考题目中有一步就是取出数字后对其进行排位,该参考题目是排3位,本题是排四位。
a=b=c=d=0;//这里注意加这样一句是为了新数输入时,不会受上一个数影响
for(int i=0;i<4;i++){
temp=n%10,n/=10;
if(temp>d)
a=b,b=c,c=d,d=temp;
else if(temp>c)
a=b,b=c,c=temp;
else if(temp>b)
a=b,b=temp;
else
a=temp;
}
max=d*1000+c*100+b*10+a;
min=a*1000+b*100+c*10+d;
n=max-min;
2、对于4位数字中有多个0,我们首先想的是哪一个数0在高位,首先max作为顺序(大到小)0肯定在后面,可以不做处理,其次n是每一轮的输出,下一轮的输入,根据题目输入而定(测试数据中有“3”这种,其实也应该考虑,但是这里没考虑。)最明显的就是min这个逆序数,0放在前面,最可能出现不够四位的情况,所以对min的输出进行处理。
if(n==0)
{cout<<max<<" - "<<min<<" = "<<0<<0<<0<<0<<endl;break;}
else
{
cout<<max<<" - ";
if(min>1000) cout<<min;
else if(min>100) cout<<0<<min;
else if(min>10) cout<<0<<0<<min;
else if(min>0) cout<<0<<0<<0<<min;
cout<<" = "<<n<<endl;
(三)问题源码
#include <iostream>
using namespace std;
int main()
{
int n,a,b,c,d,temp,max,min;
cin>>n;
do
{
a=b=c=d=0;
for(int i=0;i<4;i++){
temp=n%10,n/=10;
if(temp>d)
a=b,b=c,c=d,d=temp;
else if(temp>c)
a=b,b=c,c=temp;
else if(temp>b)
a=b,b=temp;
else
a=temp;
}
max=d*1000+c*100+b*10+a;
min=a*1000+b*100+c*10+d;
n=max-min;
if(n==0)
{cout<<max<<" - "<<min<<" = "<<0<<0<<0<<0<<endl;break;}
else
{
cout<<max<<" - ";
if(min>1000) cout<<min;
else if(min>100) cout<<0<<min;
else if(min>10) cout<<0<<0<<min;
else if(min>0) cout<<0<<0<<0<<min;
cout<<" = "<<n<<endl;
}
}while(n!=6174);
return 0;
}