初读java编程思想,看到了吸血鬼数字的问题
public class DemoApplication1 {
public static void main(String[] args) {
demo();
}
/**
* 4位数吸血鬼数字
*/
public static void demo() {
int result = 0;
StringBuilder content = new StringBuilder("");
int[] a = new int[10000];
for (int i = 1; i < 100; i++) {
for (int j = 1; j < 100; j++) {
result = i * j;
if (result > 1000 && result < 10000 && result % 100 != 0) {
if (testEquals(i, j, result, content)) {
System.out.println(i + "*" + j + "=" + result);
}
}
}
}
}
private static boolean testEquals(int a, int b, int c, StringBuilder content) {
int[] aAndB = toIntArray(a, b);
int[] cArr = toIntArray(c);
sort(aAndB);
sort(cArr);
String resultString = Arrays.toString(aAndB) + Arrays.toString(cArr) + c;
if (testEquals(aAndB, cArr) && !content.toString().contains(resultString)) {
content.append(",").append(resultString);
return true;
}
return false;
}
private static boolean testEquals(int[] a, int[] b) {
for (int i = 0; i < 4; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
private static int[] toIntArray(int a) {
int[] result = new int[4];
result[0] = a / 1000;
result[1] = a % 1000 / 100;
result[2] = a % 1000 % 100 / 10;
result[3] = a % 10;
return result;
}
private static int[] toIntArray(int a, int b) {
int[] result = new int[4];
result[0] = a / 10;
result[1] = a % 10;
result[2] = b / 10;
result[3] = b % 10;
return result;
}
private static int[] sort(int[] source) {
if (source == null || source.length != 4) {
throw new RuntimeException("source int [] error");
}
int temp = 0;
for (int i = 0; i < 4; i++) {
for (int j = i; j < 4; j++) {
if (source[j] < source[i]) {
temp = source[j];
source[j] = source[i];
source[i] = temp;
}
}
}
return source;
}
}