-
题目链接:数字黑洞 (20)
-
题目描述
给定任一个各位数字不完全相同的4位正整数,如果我们先把4个数字按非递增排序,再按非递减排序,然后用第1个数字减第2个数字,将得到一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的6174,这个神奇的数字也叫Kaprekar常数。
-
例如,我们从6767开始,将得到
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
… … -
现给定任意4位正整数,请编写程序演示到达黑洞的过程。
-
输入描述:
输入给出一个(0, 10000)区间内的正整数N。
-
输出描述:
如果N的4位数字全相等,则在一行内输出“N - N = 0000”;否则将计算的每一步在一行内输出,直到6174作为差出现,输出格式见样例,每行中间没有空行。注意每个数字按4位数格式输出。
-
输入例子:
6767
-
输出例子:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174 -
满分代码
#include <iostream> #include <algorithm> #include <string> #include <map> #include <cstdlib> using namespace std; char data[4] = {'0','0','0','0'}; //非递增 bool cmp1(char a,char b) { return a>=b; } void stoc(string str) { //先清空一下 data[3] = data[2] = data[1] = data[0] = '0'; //这样处理,保证str长度变化不影响正确性 int i = 3; while(str.length()>0) { data[i] = str[str.length()-1]; i--; str.pop_back(); } } int main() { string str; cin>>str; stoc(str); //特殊情况,全等 if(data[0]==data[1] && data[0]==data[2] && data[0]==data[3]) { cout<<"N - N = 0000"; return 0; } //特殊情况,6174 if(atoi(data)==6174) { cout<<"7641 - 1467 = 6174"; return 0; } int t,b,s; while(atoi(data)!=6174) { sort(data,data+4,cmp1); b = atoi(data); reverse(data,data+4); s = atoi(data); t = b-s; printf("%04d - %04d = %04d\n",b,s,t); stoc(to_string(t)); } return 0; }
-
说明
-
涉及排序,考虑用
sort
函数,所以用数组存这个数 -
输出的时候,如果数字位数少于4要高位补0,使用
printf("%04d - %04d = %04d\n",b,s,t);
这种写法 -
类型转换
-
string 类型转 int、long、long long、float、double、long double
头⽂件#include<string>
:stoi
、stol
、stoll
、stof
、stod
、stold
-
char c[10] 类型转 int、long、long long
头⽂件#include <cstdlib>
:atoi
、atol
、atoll
-
int、long、long long、float、double、long double 转 string
头⽂件#include<string>
:to_string
-
-
reverse
函数- 头文件
#include <algorithm>
- 用法
reverse(it1,it2);
将指针或容器迭代器(it1,it2]
间的数据就地反转 - 常用于数组、string、vector等的就地反转
- 头文件
-
PAT乙级 —— 1009 数字黑洞 (20)
最新推荐文章于 2021-12-06 20:21:54 发布