1019 数字黑洞 (20 分)

题目链接:

https://pintia.cn/problem-sets/994805260223102976/problems/994805302786899968

思路:本题就按照题目的意思来编写就好了,需要注意的地方可看填坑日记(*^▽^*)

填坑日记:有一个测试点是直接输入6174的,所以在为6174的时候还是要按照步骤来输出,要注意自己的判断语句;再是补0的问题,不满4位数需要补上0,可以用insert()函数来写,比较方便。要注意的地方大概就这两点。

tips:1,2,3,4,5,.:递增排列 ;9,8,7,6,5.:递减排列 ;1,2,3,3,4,5,8,8,.:非递减排列 ;9,8,7,7,6,5,5,2,1,.:非递增排列

代码:

#include<iostream>
#include<algorithm>
using namespace std;
char cmp1(char a,char b)
{
	return a>=b;
}
char cmp2(char a,char b)
{
	return a<=b;
}
int main()
{
	string s,s1,s2;
	cin>>s;
	s.insert(0, 4 - s.length(), '0');
	int m,n,l;
	sort(s.begin(),s.end(),cmp1);
	m=stoi(s);
	sort(s.begin(),s.end(),cmp2);
	n=stoi(s);
	l=m-n;
	if(m-n==0){
		s1=to_string(m);		
		s1.insert(0, 4 - s1.length(), '0');
		s2=to_string(n);
		s2.insert(0,4-s2.length(),'0');
		s=to_string(l);
		s.insert(0,4-s.length(),'0');
		cout<<s1<<" - "<<s2<<" = "<<s<<endl;
	}
	else if(l==6174)
	{
		s1=to_string(m);		
		s1.insert(0, 4 - s1.length(), '0');
		s2=to_string(n);
		s2.insert(0,4-s2.length(),'0');
		s=to_string(l);
		s.insert(0,4-s.length(),'0');
		cout<<s1<<" - "<<s2<<" = "<<s<<endl;
	}
	else
	{
		while(l!=6174)
		{
			l=m-n;
			s1=to_string(m);		
			s1.insert(0, 4 - s1.length(), '0');
			s2=to_string(n);
			s2.insert(0,4-s2.length(),'0');
			s=to_string(l);
			s.insert(0,4-s.length(),'0');
			cout<<s1<<" - "<<s2<<" = "<<s<<endl;			
			sort(s.begin(),s.end(),cmp1);
			m=stoi(s);
			sort(s.begin(),s.end(),cmp2);
			n=stoi(s);
		}
		
	}
		

 } 

下面有到了膜大佬的时候了:::::

放链接:https://www.liuchuo.net/archives/541

放代码:

#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(char a, char b) {return a > b;}
int main() {
    string s;
    cin >> s;
    s.insert(0, 4 - s.length(), '0');
    do {
        string a = s, b = s;
        sort(a.begin(), a.end(), cmp);
        sort(b.begin(), b.end());
        int result = stoi(a) - stoi(b);
        s = to_string(result);
        s.insert(0, 4 - s.length(), '0');
        cout << a << " - " << b << " = " << s << endl;
    } while (s != "6174" && s != "0000");
    return 0;
}

不活了不活了,我的代码长度有大神的3倍啊。。。。。。。观摩了一下,感觉我的代码冗余项过多,而且之前我的填坑日记里说的6174的问题,其实可以用do while语句解决呀!!!计算了之后再进行判断,归入循环内,一样的代码我写了3遍也是很胖胖了2333333333。吸取教训,继续加油吧。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值