zoukankan      html  css  js  c++  java
  • PAT——1019. 数字黑洞

    给定任一个各位数字不完全相同的4位正整数,如果我们先把4个数字按非递增排序,再按非递减排序,然后用第1个数字减第2个数字,将得到一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的6174,这个神奇的数字也叫Kaprekar常数。

    例如,我们从6767开始,将得到

    7766 - 6677 = 1089
    9810 - 0189 = 9621
    9621 - 1269 = 8352
    8532 - 2358 = 6174
    7641 - 1467 = 6174
    ... ...

    现给定任意4位正整数,请编写程序演示到达黑洞的过程。

    输入格式:

    输入给出一个(0, 10000)区间内的正整数N。

    输出格式:

    如果N的4位数字全相等,则在一行内输出“N - N = 0000”;否则将计算的每一步在一行内输出,直到6174作为差出现,输出格式见样例。注意每个数字按4位数格式输出。

    输入样例1:

    6767
    

    输出样例1:

    7766 - 6677 = 1089
    9810 - 0189 = 9621
    9621 - 1269 = 8352
    8532 - 2358 = 6174
    

    输入样例2:

    2222
    

    输出样例2:

    2222 - 2222 = 0000

     1 package com.hone.basical;
     2 
     3 import java.util.Arrays;
     4 import java.util.Scanner;
     5 
     6 /**
     7  * 原题目:https://www.patest.cn/contests/pat-b-practise/1019
     8  * @author Xia
     9  * 核心:其实就是一个对数据的处理(利用两个函数处理升序和降序)
    10  */
    11 
    12 public class basicalLevel1019NumBlackHole{
    13     public static void main(String[] args) {
    14         Scanner s = new Scanner(System.in);
    15         int x = s.nextInt();
    16         int diff = ds(x)-cs(x);
    17         if (diff == 0) {
    18             System.out.printf("%04d - %04d = %04d
    ",ds(x),cs(x),diff);
    19         }
    20         else{
    21             int diff2;
    22             do {
    23             diff2 = ds(x)-cs(x);
    24             System.out.printf("%04d - %04d = %04d
    ",ds(x),cs(x),diff2);
    25             x = diff;
    26             } while (diff2!=6174);
    27         }
    28     }
    29     //升序
    30     private static int cs(int x) {
    31         int[] a = new int[4];
    32         a[0] = x/1000;
    33         a[1] = x/100%10;
    34         a[2] = x/10%10;
    35         a[3] = x%10;
    36         Arrays.sort(a);            //升序
    37         int sum = a[0]*1000+a[1]*100+a[2]*10+a[3];
    38         return sum;
    39     }
    40     //升序
    41     private static int ds(int x) {
    42         int[] a = new int[4];
    43         a[0] = x/1000;
    44         a[1] = x/100%10;
    45         a[2] = x/10%10;
    46         a[3] = x%10;
    47         Arrays.sort(a);            //升序
    48         int sum = a[3]*1000+a[2]*100+a[1]*10+a[0];
    49         return sum;
    50     }
    51 }  


  • 相关阅读:
    Protocol Buffer技术详解(语言规范)
    google protobuf 简单实例
    advStringGrid单元格文字垂直居中
    java中两个字符串如何比较大小
    List集合去除重复对象及equals()、hashCode()方法的作用
    Delphi中使用ActiveX的一些心得
    java List去重方式及效率对比
    Visual Studio Code 调整字体大小
    用最简单的例子实现jQuery图片即时上传
    Linux下绝对经典的命令
  • 原文地址:https://www.cnblogs.com/xiaxj/p/7978755.html
Copyright © 2011-2022 走看看