1019 数字黑洞 (20 分)

320 阅读1分钟

题目链接

  1. 对输入的数据进行补全,如果少于4为,则以0在左边补齐
  2. 采用循环判断每次的结果是否应该停止输出(结果为0或6174则应该停止输出)

c++代码

#include <iostream>
#include<string>
#include<vector> 
#include<queue>
#include<map>
#include <algorithm>
using namespace std;
bool cmp(const char& a, const char& b) {
	return a > b;
}

int main() {
	string s;
	int res;
	cin >> s;
	s.insert(0, 4 - s.length(), '0');
	string a, b;
	do {
		a = s;
		b = s;
		sort(a.begin(), a.end(), cmp);
		sort(b.begin(), b.end());
		res = stoi(a) - stoi(b);
		s = to_string(res);
		s.insert(0, 4 - s.length(), '0');
		cout << a << " - " << b << " = " << s << endl;
	} while (s != "6174"&s != "0000");
	return 0;
}

python3代码

def main():
    s = '{:0>4}'.format(input())


    while True:
        str_a = ("".join(sorted(list(s)))) # 默认从小到排序
        str_b = ("".join(sorted(list(s), reverse=True))) # 从大到小排序
        a = int(str_a)
        b = int(str_b)
        c = b - a
        str_c = '{:0>4}'.format(str(c))
        print('{} - {} = {}'.format(str_b,str_a,str_c))
        s = str_c
        if(c ==0 or c == 6174):
            break
main()