PAT答案(數字黑洞)

題目鏈接

https://www.nowcoder.com/pat/6/problem/4045

代碼

#include<iostream>
#include<math.h>
#include<algorithm>
#include<iomanip>
#include<string.h>
#define LENGTH 4
using namespace std;

bool myfun(int i, int j) {
    return i>j;
}
int main() {
    int n, flag = 1;
    int a[4];
    memset(a, 0, sizeof(a));
    scanf("%d", &n);
    int result = n;
    while(result != 6174 || flag) {
        int i=0;
        int big_value=0, small_value=0;
        while(i < LENGTH) {
            a[i] = result % 10;
            result /= 10;
            i++;
        }
        if( (a[0] == a[1]) && (a[0]== a[2])  && (a[0]== a[3])) {
            cout << setw(4) << setfill('0') << n << " - " << setw(4) << setfill('0') << n << " = " << setw(4) << setfill('0') << "0000" << endl;
            break;
        }
        sort(a, a+LENGTH, myfun);
        for(int i=0; i<LENGTH; i++) {
            big_value += a[i] * pow(10, LENGTH-i-1);
            small_value += a[LENGTH-i-1] * pow(10, LENGTH-i-1);
        }
        result = big_value - small_value;
        cout << setw(4) << setfill('0') << big_value << " - " << setw(4) << setfill('0') << small_value << " = " << setw(4) << setfill('0') << result << endl;
        flag = 0;
    }
    return 0;
}
發佈了151 篇原創文章 · 獲贊 56 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章