没有午休写出来了。结果告知我不是在校学生,把资料改了还是不能参与挑战,只能贴出来了。
package test;
import java.util.Arrays;
import java.util.Scanner;
public class CustomIntegerOrder {
/**
* 求出各数字之和
*
* @param x
* @return
*/
public static int w(int x) {
if (x < 0)
return 0;
int s = 0;
do {
int y = x % 10;
s += y;
x = x / 10;
} while (x > 0);
return s;
}
/**
* 如果x<y,返回true
*
* @param x
* @param y
* @return
*/
public static boolean compare(int x, int y) {
if (w(x) < w(y)) {
return true;
} else if (w(x) == w(y)) {
boolean bl = false;
String sx = Integer.toString(x);
String sy = Integer.toString(y);
char[] ax = sx.toCharArray();
char[] ay = sy.toCharArray();
int lx = ax.length;
int ly = ay.length;
int l = lx < ly ? lx : ly;
for (int i = 0; i < l; i++) {
if (ax[i] < ay[i]) {
bl = true;
break;
} else if (ax[i] == ay[i]) {
continue;
} else {
bl = false;
break;
}
}
return bl;
}
return false;
}
/**
* 生成长度为x的数组
*
* @param x
*/
public static int[] generateAry(int x) {
int[] ary = new int[x];
for (int i = 0; i < x; i++) {
// ary[i] = (int) (Math.random() * 1e5 + 1);
ary[i] = i + 1;
}
return ary;
}
/**
* 可以用来检验结果是否正确
*
* @param ary
*/
public static void outputAry(int[] ary) {
System.out.println("原数组:" + Arrays.toString(ary));
int[] temp = new int[ary.length];
for (int i = 0; i < ary.length; i++) {
temp[i] = w(ary[i]);
}
System.out.println("各数和:" + Arrays.toString(temp));
}
/**
* 排序后并输出
*
* @param x
* @param k
*/
public static void compareAndOutput(int x, int k) {
int[] ary = generateAry(x);
// outputAry(ary);
System.out.println("原数组:" + Arrays.toString(ary));
int l = ary.length;
int temp;
for (int i = 0; i < l; i++) {
for (int j = i + 1; j < l; j++) {
if (compare(ary[j], ary[i])) {
temp = ary[j];
ary[j] = ary[i];
ary[i] = temp;
}
}
}
// outputAry(ary);
System.out.println("排序后:" + Arrays.toString(ary));
System.out.println(k + "所在的位置:" + findK(ary, k));
System.out.println("第" + k + "位的数是:" + ary[k - 1]);
}
/**
* 找到k所在的位置
*
* @param ary
* @param k
* @return
*/
public static int findK(int[] ary, int k) {
for (int i = 0; i < ary.length; i++) {
if (k == ary[i]) {
return i + 1;
}
}
return 0;
}
public static void main(String[] args) {
System.out.println("请输入数组长度n:");
Scanner in = new Scanner(System.in);
int x = in.nextInt();
System.out.println("请输入1-n的数字k:");
in = new Scanner(System.in);
int k = in.nextInt();
compareAndOutput(x, k);
}
}