pat乙级第九题 数字黑洞

注意这段代码中的quwei函数 这个函数可以把整形轻松的转换为字符串,十分高效,主要是使用了sprintf函数
sprintf( char* buf , const char* format , … ) ; 比起printf, 前面多了一个char* buf , 就是把格式化的子串写到buf中

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>//输入输出
#include <stdio.h>
#include <stdlib.h>//算法
#include <algorithm>
#include <string>//字符串
#include <string.h>
//#include <syslib.h>
#include <math.h>//数学

#include <stack>//模板
#include <queue>
#include <vector>

using namespace std;
const int MaxSize = 4;
const int Max = 100;

int shu1[4],shu2[4],shu3[4],ansarr[4];//shu1存储最初数据,以及在排序前的数据,shu2和shu3 始终存储排序后的数据,ansarr 用来存储ans的每一位;
char buf[Max];
bool cmp1(int a, int b) {
    if (a != b) return a <= b;
    //if (a != b) return a >= b;
    return false;
}

bool cmp2(int a, int b) {
    if (a != b) {
        return a >= b;
    }
    return false;
}

int* arrcopy(int *a,int *b,int len) {
    for (int i = 0; i < len; i++) {
        b[i] = a[i];
    }
    return b;
}

void quwei(int a) {
    sprintf(buf,"%04d",a);
    int len = strlen(buf);
    for (int i = 0; i < len; i++) {
        shu1[i] = buf[i] - '0';
    }
    for (int i = len; i < 4; i++) {
        shu1[i] = 0;
    }

}

/*void quwei(int a) {
    char * s;
    s = itoa(a,buf,10);
    int len = strlen(s);
    for (int i = 0; i < len; i++) {
        shu1[i] = s[i] - '0';
    }
    for (int i = len; i < 4; i++) {
        shu1[i] = 0;
    }

}*/
int zhi(int *a) {
    int num1 = a[0] * 1000 + a[1] * 100 + a[2] * 10 + a[3];
    return num1;
}

void prtequ(int *a,int *b) {//a和b始终是指向shu2 和shu3 的指针。
    int ans = 0;
    while (ans!=6174) {
        a = arrcopy(shu1, a, 4);
        b = arrcopy(shu1, b, 4);
        sort(a, a + 4, cmp1);
        sort(b, b + 4, cmp2);
        int num1 = zhi(a);
        int num2 = zhi(b);
        //num1 = (num1 > num2) ? num1 : num2;
        //num2 = (num2 < num1) ? num2 : num1;
        ans = num2 - num1;
        printf("%04d - %04d = %04d\n", num2, num1, ans);
        quwei(ans);
    }
    return;
}


int main()
{
    freopen("Text.txt", "r", stdin);
    while (scanf("%01d%01d%01d%01d",&shu1[0],&shu1[1],&shu1[2],&shu1[3])!=EOF) {
        prtequ(shu2, shu3);


    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wi8ruk48/article/details/82081161