PAT(B) 1019 数字黑洞(Java & C)

    xiaoxiao2022-07-08  147

    题目链接:https://pintia.cn/problem-sets/994805260223102976/problems/994805302786899968


    题解

    输入正整数n后,将n转成int型数组nArr[4]用Arrays.sort(int[] a)方法将数组nArr非递减排序很显然,非递减排序得到的是最小值,非递增排序得到的是最大值不需要再用排序方法将nArr进行非递增排序,直接逆序“组合”即可。具体见代码当相减的差result为6174或者0时,结束do - while循环

    Java代码

    /** * Score 20 * Run Time 118ms * @author wowpH * @version 1.2 */ import java.util.Arrays; import java.util.Scanner; public class Main { // 非递减,最小值 // 非递增,最大值 // 最大值最小值相减的结果 private int minN, maxN, result; private int[] nArr;// 数组类型的n public Main() { Scanner sc = new Scanner(System.in); int n = sc.nextInt();// 输入正整数n sc.close(); nArr = new int[4]; // 4位 result = n; do { step(); } while (6174 != result && 0 != result);// 结束条件 } private void step() { // 转成数组类型 for (int i = 3; i >= 0; i--) { nArr[i] = result % 10; result /= 10; } Arrays.sort(nArr); // 非递减排序 minN = maxN = 0; for (int i = 0; i < 4; i++) { minN = minN * 10 + nArr[i]; // 顺序转成最小值 } for (int i = 3; i >= 0; i--) { maxN = maxN * 10 + nArr[i]; // 逆序转成最大值 } result = maxN - minN; // 结果 outputStep(); // 输出当前步骤的减法算式 } // 输出每一步 private void outputStep() { if (0 == result) { System.out.println(maxN + " - " + minN + " = 0000"); } else { System.out.printf("d - ", maxN); System.out.printf("d = ", minN); System.out.printf("d\n", result); } } public static void main(String[] args) { new Main(); } }

    C代码

    /******************************************************************** Description: PAT(B)1019数字黑洞 Score: 20 Run Time: 2ms Author: wowpH Id: pfdvnah Date: 2019-11-10 15:49:10 From: https://blog.csdn.net/pfdvnah/article/details/90456767 ********************************************************************/ #include <stdio.h> #include <stdlib.h> #define N_LEN 4 void output_step(int result, int max, int min); int compare(const int* a, const int* b); int step(int result); int main(void) { int n; // scanf_s("%d", &n); scanf("%d", &n); int result = n; do { result = step(result); } while (6174 != result && 0 != result); return 0; } void output_step(int result, int max, int min) { if (0 == result) { printf("d - d = 0000\n", max, min); } else { printf("d - ", max); printf("d = ", min); printf("d\n", result); } } int compare(const int* a, const int* b) { return (*a) < (*b) ? -1 : 1; } int step(int result) { int arr[N_LEN]; for (int i = 0; i < N_LEN; ++i) { arr[i] = result % 10; result /= 10; } qsort(arr, N_LEN, sizeof(int), compare); int max = 0; for (int i = N_LEN - 1; i >= 0; --i) { max = max * 10 + arr[i]; } int min = 0; for (int i = 0; i < N_LEN; ++i) { min = min * 10 + arr[i]; } result = max - min; output_step(result, max, min); return result; }

    版权声明:

    转载请于首页注明链接形式的PAT(B) 1019 数字黑洞(Java)——wowpH;代码原创,公开引用不能删除首行注释(作者,版本号,时间等信息);如果有疑问欢迎评论留言,尽量解答。
    最新回复(0)