PAT 甲级 1069 The Black Hole of Numbers (20 分)(内含别人string处理的精简代码)
Posted caiyishuai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT 甲级 1069 The Black Hole of Numbers (20 分)(内含别人string处理的精简代码)相关的知识,希望对你有一定的参考价值。
For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in non-increasing order first, and then in non-decreasing order, a new number can be obtained by taking the second number from the first one. Repeat in this manner we will soon end up at the number 6174
-- the black hole of 4-digit numbers. This number is named Kaprekar Constant.
For example, start from 6767
, we‘ll get:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...
Given any 4-digit number, you are supposed to illustrate the way it gets into the black hole.
Input Specification:
Each input file contains one test case which gives a positive integer N in the range (.
Output Specification:
If all the 4 digits of N are the same, print in one line the equation N - N = 0000
. Else print each step of calculation in a line until 6174
comes out as the difference. All the numbers must be printed as 4-digit numbers.
Sample Input 1:
6767
Sample Output 1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
Sample Input 2:
2222
Sample Output 2:
2222 - 2222 = 0000
题意:
给一个数组n,先对各个数字位从大到小排序得到a,然后逆置得到b,计算a-b,得到c,重复上述过程,直到得到6174,或者,对于特例,四个数字位完全相同,那么输出0000。
题解:
刚开始输入的数字可能不足四位要自动补0 以后的结果可能也不足四位都要自动补0
结果是0或者6174都是要退出的
一开始没考虑到6174,测试点5没过,后来想到了
AC代码:
#include<iostream> #include<algorithm> using namespace std; int n; int a[10]; int main(){ cin>>n; int big=0; int small=0; int x=n; int k=0,f; if(x==6174){ printf("7641 - 1467 = 6174"); return 0; } while(x!=6174){ k=0; big=0; small=0; while(x>=10){ a[++k]=x%10; x/=10; } a[++k]=x; while(k<4){ a[++k]=0; } sort(a+1,a+1+4); for(int i=1;i<=4;i++){ big=big*10+a[5-i]; small=small*10+a[i]; } x=big-small; printf("%04d - %04d = %04d ",big,small,x); if(x==0) break; } return 0; }
更简洁的string处理的代码:
#include<bits/stdc++.h> using namespace std; bool cmp(char a,char b) { return a>b; } int main(void) { string s; cin>>s; s.insert(0,4-s.size(),‘0‘); do{ string a=s,b=s; sort(a.begin(),a.end(),cmp); sort(b.begin(),b.end()); int diff=stoi(a)-stoi(b); s=to_string(diff); s.insert(0,4-s.size(),‘0‘); cout<<a<<" - "<<b<<" = "<<s<<endl; }while(s!="6174"&&s!="0000"); return 0; ———————————————— 版权声明:本文为CSDN博主「Imagirl1」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/Imagirl1/article/details/82261213
以上是关于PAT 甲级 1069 The Black Hole of Numbers (20 分)(内含别人string处理的精简代码)的主要内容,如果未能解决你的问题,请参考以下文章
pat 1069 The Black Hole of Numbers(20 分)
PAT1069. The Black Hole of Numbers
PAT Advanced 1069 The Black Hole of Numbers (20分)
1069. The Black Hole of Numbers (20)模拟——PAT (Advanced Level) Practise