您的位置:首页 > 其它

1019. 数字黑洞 (20)——printf()输出位数控制

2016-10-25 16:20 246 查看
1、题目描述

给定任一个各位数字不完全相同的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位数格式输出。

输入样例1:
6767

输出样例1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174

输入样例2:
2222

输出样例2:
2222 - 2222 = 0000


2、思路分析
此题关键是printf输出时位数的控制。
3、C++代码
#include<iostream>  //priority_queue的灵活应用;
#include<algorithm>  //有一个输入是6174的情况,也需要输出一个步骤;
#include<string.h>
#include<stdio.h>
#include<vector>
#include<string>
#include<stack>
#include<queue>
#include<math.h>
#include<map>
using namespace std;

int N;
priority_queue<int> Q1;
priority_queue<int,vector<int>,greater<int>> Q2;

void Input(){
scanf("%d",&N);
}

void Process(){
if(N%1111==0)
printf("%04d - %04d = %04d\n",N,N,0);
else if(N==6174)
printf("7641 - 1467 = 6174\n");
else{
int n1,n2,i,t;
while(N!=6174){
for(i=0;i<4;i++){
t=N%10;
Q1.push(t);
Q2.push(t);
N/=10;
}
n1=n2=0;
while(!Q1.empty()){
n1=n1*10+Q1.top();
Q1.pop();
}
while(!Q2.empty()){
n2=n2*10+Q2.top();
Q2.pop();
}
N=n1-n2;
printf("%04d - %04d = %04d\n",n1,n2,N);
}
}
}

void Display(){

}

int main(){
//	while(true){
Input();
Process();
//	Display();
//	}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: