算法求解 1,2,3,4,5,6,8,9八个数字组成两个四位数,求两个四位数的差的最小值。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 这种东西还是递归吧: private static int min; private static String value; public static void main(String[] args) { int[] nums = { 1, 2, 3, 4, 5, 6, 8, 9 }; int[] result = new int[nums.length]; split(nums, result, 0); System.out.println(value); } public static void split(int[] nums, int[] result, int count) { if (count == nums.length) { int firstNum = result[0] * 1000 + result[1] * 100 + result[2] * 10 + result[3]; int secondNum = result[4] * 1000 + result[5] * 100 + result[6] * 10 + result[7]; int sub = Math.abs(firstNum - secondNum); if (min == 0) { min = sub; } else { if(min>sub){ value=firstNum+","+secondNum+"==>"+sub; min=sub; } } } for (int i = 0; i < nums.length; i++) { int num = nums[i]; if (num != 0) { result[count] = nums[i]; nums[i] = 0; split(nums, result, count + 1); nums[i] = num; } } }输出:4986,5123==>137 我的VISUAL STUDIO 2008只有VISUAL BASIC,C#,C++,数据库,没有J#啊? java2D的问题 关于用java写的递归函数的问题~~ 表单提交 !100 有关MQ的问题? 如何通过反射机制,动态调用静态变量? 帮帮忙,远程方法调用的问题 用什么方法删除JTextArea其全部内容?? idea maven引入jar包失败,求大神执导 关于byte[]的问题 求助。。给思路
private static String value;
public static void main(String[] args) {
int[] nums = { 1, 2, 3, 4, 5, 6, 8, 9 };
int[] result = new int[nums.length];
split(nums, result, 0);
System.out.println(value); } public static void split(int[] nums, int[] result, int count) {
if (count == nums.length) {
int firstNum = result[0] * 1000 + result[1] * 100 + result[2] * 10
+ result[3];
int secondNum = result[4] * 1000 + result[5] * 100 + result[6] * 10
+ result[7];
int sub = Math.abs(firstNum - secondNum);
if (min == 0) {
min = sub;
} else {
if(min>sub){
value=firstNum+","+secondNum+"==>"+sub;
min=sub;
}
}
}
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
if (num != 0) {
result[count] = nums[i];
nums[i] = 0;
split(nums, result, count + 1);
nums[i] = num;
}
}
}输出:4986,5123==>137