【算法题目】编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是100的程序,并输出所有的可能性。
public static void main(String[] args) { String[] sym = new String[]{"+", "-", ""}; String[] nums = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9"}; int count = 0; int len = sym.length; for (int a=0; a<len; a++) for (int b=0; b<len; b++) for (int c=0; c<len; c++) for (int d=0; d<len; d++) for (int e=0; e<len; e++) for (int f=0; f<len; f++) for (int g=0; g<len; g++) for (int h=0; h<len; h++){ String equation = nums[0] + sym[a] + nums[1] + sym[b] + nums[2] + sym[c] + nums[3]
+ sym[d] + nums[4] + sym[e] + nums[5] + sym[f] + nums[6] + sym[g] + nums[7] + sym[h] + nums[8]; int sum = getSum(equation); if (sum == 10){ System.out.println(equation + " = " + sum); count++; } } System.out.println("一共有 " + count + " 条公式可以计算出来"); } public static int getSum(String equation){ int sum = 0; String[] addArr = equation.split("\\+"); for (String str : addArr){ if (str.indexOf("-") != -1){ String[] minusArr = str.split("\\-"); for (int i=0; i<minusArr.length; i++){ if(i == 0){ sum += Integer.parseInt(minusArr[i]); } else { sum = (sum - Integer.parseInt(minusArr[i])); } } } else { sum += Integer.parseInt(str); } } return sum; }