2017-11-06 14:54

# B1019. 数字黑洞，关于数组排降序，得到最大值问题？

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

``````import java.util.Scanner;
import java.util.Arrays;

public class B1019 {
/*将数组转化为数字*/
public static int tonumber(int []n)
{
int N = 0;
for (int x = 0; x < 4; x++)
{
N = N * 10 + n[x];
}
return N;
}

public static int[] toarray(int num)
{
int []array = new int[4];
for (int i = 0; i < 4; i++)
{
array[i] = num % 10;
num = num / 10;
}
return array;
}

public static int[] mintomax(int []N)
{
int []X = new int[4];
for (int j = 0; j < 4; j++)
{
X[j] = N[3-j];
}
return X;
}

public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num = in.nextInt();
while(num != 6174 || num != 0)
{
int []number = new int[4];
number = toarray(num);/*将第一个数字转化成数组*/
/*sort()升序*/
Arrays.sort(number);    /*直接修改number数组顺序，不可以赋值给任何具体的*/
int max;
int min;
int[] minarray = new int[4];
int[] maxarray = new int[4];
min = tonumber(number);
/*没有降序库，将升序的数组每一个元素倒着排，输出数组*/
minarray = toarray(min);
maxarray = mintomax(minarray);
max = tonumber(maxarray);
num = max - min;
System.out.printf("%04d - %04d = %04d\n",  max, min, num);
if (num == 6174 || num == 0)
{
break;
}
}
in.close();
}
}

``````

• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 2条回答默认 最新

• 逗比123号 2017-11-07 01:25

你的toArray方法得到的是倒序的，把array[i]换成array[3-i]

点赞 打赏 评论
• hycf 2017-11-07 02:43

`````` package pratice;

import java.util.Scanner;
import java.util.Arrays;

public class Main_数字黑洞 {
/*将数组转化为数字*/
public static int tonumber(int []n)
{
int N = 0;
for (int x = 0; x < 4; x++)
{
N = N * 10 + n[x];
}
return N;
}

public static int[] toarray(int num)
{
int []array = new int[4];
for (int i = 0; i < 4; i++)
{
array[3-i] = num % 10;
num = num / 10;
}
return array;
}

public static int[] mintomax(int []N)
{
int []X = new int[4];
for (int j = 0; j < 4; j++)
{
X[j] = N[3-j];
}
return X;
}

public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num = in.nextInt();
while(num != 6174 || num != 0)
{
int []number = new int[4];
number = toarray(num);/*将第一个数字转化成数组*/
/*sort()升序*/
Arrays.sort(number);    /*直接修改number数组顺序，不可以赋值给任何具体的*/
int max;
int min;
int[] minarray = new int[4];
int[] maxarray = new int[4];
min = tonumber(number);
/*没有降序库，将升序的数组每一个元素倒着排，输出数组*/
minarray = toarray(min);
maxarray = mintomax(minarray);
max = tonumber(maxarray);
num = max - min;
System.out.printf("%04d - %04d = %04d\n",  max, min, num);
if (num == 6174 || num == 0)
{
break;
}
}
in.close();
}
}

``````
点赞 打赏 评论