排序相减

来源:互联网 发布:淘宝店铺付费引流 编辑:程序博客网 时间:2024/05/16 06:54

“排序相减”操作是指对于任意一个四位数n,将四个数字分别进行顺序排序和逆序排序,得到两个数取相减后结果的绝对值n1,然后继续将n1中的四个数字进行顺序排序和逆序排序,得到两个数取相减后结果的绝对值n2,以此类推,最后总会得到一个数字黑洞,无法跳出。

 

例如:样例2中4176 = 6532 - 2356

Input
第一行输入一个整数T,表示数据组数(1<T<10000);第二行输入一个正整数n(1000<=n<=9999)和一个正整数k(1<=k<=100),表示操作次数;
Output
对于每组数据,输出对于开始的数据n在第k次“排序相减”后结果绝对值。
Input示例
21234 23562 1
Output示例
8352

4176

#include <iostream>#include <stdlib.h>#include <string.h>#include <stdio.h>#include <algorithm>using namespace std;int t;int k;char input[10];void cal(char *p){    int len = strlen(p);    sort(p, p + len);    int left = 0;    int right = 0;    for (int i = 0; i < len; i++)    {        left = left * 10 + p[i] - '0';        right = right * 10 + p[len - 1 - i] - '0';    }        sprintf(p, "%d", right - left);}int main(){    cin >> t;    for (int i = 0; i < t; i++)    {        cin >> input >> k;        for (int j = 0; j < k; j++)                {            cal(input);        }                cout << input << endl;    }    return 0;}


原创粉丝点击