1 2 3 4 5 6 7 8 9 = 110 要求数字之间只能为 + 或 - 或 把数字连接起来 ,列出所有可能性
1 2 3 4 5 6 7 8 9 = 110 要求数字之间只能为 + 或 - 或 把数字连接起来 ,列出所有可能性
public class Test { String strFormula = ""; public void addsign(int a){ if(a == 0) strFormula += "+"; else if(a == 1) strFormula += "-"; else strFormula += ""; } public void compute(){ int sum = 0; String number = ""; String sign = ""; for (int i = 0; i < strFormula.length(); i++) { char h = strFormula.charAt(i); if(h >= '1' && h <= '9'){ number += String.valueOf(h); }else{ if(sign.equals("")){ sign = String.valueOf(h); sum = Integer.parseInt(number); number = ""; }else{ if(sign.equals("+")) sum = sum + Integer.parseInt(number); else if(sign.equals("-")) sum = sum - Integer.parseInt(number); number = ""; sign = String.valueOf(h); } } } if(sum == 110) System.out.println(strFormula + sum); } public static void main(String[] srg) { Test a = new Test(); for (int i1 = 0; i1 < 3; i1++) { for (int i2 = 0; i2 < 3; i2++) { for (int i3 = 0; i3 < 3; i3++) { for (int i4 = 0; i4 < 3; i4++) { for (int i5 = 0; i5 < 3; i5++) { for (int i6 = 0; i6 < 3; i6++) { for (int i7 = 0; i7 < 3; i7++) { for (int i8 = 0; i8 < 3; i8++) { a.strFormula = "1"; a.addsign(i1); a.strFormula += "2"; a.addsign(i2); a.strFormula += "3"; a.addsign(i3); a.strFormula += "4"; a.addsign(i4); a.strFormula += "5"; a.addsign(i5); a.strFormula += "6"; a.addsign(i6); a.strFormula += "7"; a.addsign(i7); a.strFormula += "8"; a.addsign(i8); a.strFormula += "9="; a.compute(); //System.out.println(a.strFormula); } } } } } } } } } }
答案:
1+2+34+5+67-8+9=110
1+234-56-78+9=110
1-2+3+45-6+78-9=110
12+3+45+67-8-9=110
12+34+56+7-8+9=110
12-3+4-5+6+7+89=110
123+4+5+67-89=110
123+4-5-6-7-8+9=110
123-4+5-6-7+8-9=110
123-4-5+6+7-8-9=110