天天看點

【甲級PAT】-1069 The Black Hole of Numbers (20分)-數字處理題目描述思路

題目描述

1069 The Black Hole of Numbers (20分)

對于一個數字,各數字首先按非遞增順序排序得到一個四位數,再按非遞減順序排序,兩者相減得到一個新的四位數字。

這個新的數字再按之前的規律相減,知道得到6174,輸出變換的過程

思路

構造一個遞歸函數,遞歸初始的n或後來得到的新的四位數,直到結果為6174或0

注意輸入數字n的取值範圍,不一定都是4位的

#include <bits/stdc++.h>

using namespace std;
int ans;
void  f(int n)
{
    int a[7],cnt=0,A=0,B=0;
    ans=0;
    memset(a,0,sizeof(a));
    while(n)
    {
        a[cnt++]=n%10;
        n/=10;
    }
    sort(a,a+cnt,greater<int>());
    for(int i=0;i<4;i++)//直接寫4就好,寫成cnt會錯,因為不是所有n都是四位數
    {
        A=A*10+a[i];
    }
    for(int i=3;i>=0;i--)
        B=B*10+a[i];
    ans=A-B;
    printf("%04d - %04d = %04d\n",A,B,ans);
    if(ans!=6174&&ans)
    f(ans);
}
int main()
{
    #ifdef ONLINE_JUDGE
    #else
        freopen("1.txt", "r", stdin);
    #endif
    int n;
    cin>>n;
    ans=n;
    f(ans);
    return 0;
}