您的位置:首页 > 其它

算法题 趣味算式110

2013-07-04 20:24 302 查看
public class 趣味算式110 {
public static void main(String[] args) {
char[] cs = new char[17];
for (int i = 0; i != 9; ++i) {
cs[2 * i] = (char) (i + 1 + '0');
}
// System.out.println(cs);
calString(cs, 1);
}
static int n = 0;
public static void calString(char[] s, int pos) { // 插空位置为 1 3 5 7 9 11 13
// 15共八个
if (pos == 15 + 2) { // 此时插空完毕
//			try {
//				FileWriter out = new FileWriter("d:\\1.txt", true);
//				out.write(s.toString() + " ");
//				out.close();
//			} catch (FileNotFoundException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			n++;
calResult(new String(s));
return;
}

for (int i = 0; i != 3; ++i) { // i的0 1 2 分别代表 空 加 减
switch (i) {
case 0:
s[pos] = ' ';
break;
case 1:
s[pos] = '+';
break;
case 2:
s[pos] = '-';
break;
}
calString(s, pos + 2);
}

}

static void calResult(String s) {
if (s.equals(""))
return;
s = s.replaceAll(" ", "");
String data = s;
String[] ss = s.split("[^0-9]");
int sum = Integer.parseInt(ss[0]);
for (int i = 0; i != ss.length - 1; ++i) {
char op = s.charAt(ss[i].length());
if (op == '+') {
sum += Integer.parseInt(ss[i + 1]);
} else {
sum -= Integer.parseInt(ss[i + 1]);
}
s = s.substring(ss[i].length() + 1);
}
if (sum == 100) {
System.out.println(data + "=100");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: