您的位置:首页 > 其它

编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是 100 的程序,并输出所有的可能性。 例如:1 + 2 + 34 – 5 + 67 – 8 + 9 = 100

2017-09-04 09:58 846 查看
微信公众号看到了这样一个面试题:编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是 100 的程序,并输出所有的可能性。

例如:1 + 2 + 34 – 5 + 67 – 8 + 9 = 100。

以下是我的解决方案:

思路:先将字符串拆成n个字符串,字符串之间插入符号计算结果

package com.eweaver.cpms.project.common;

import java.util.ArrayList;
import java.util.List;

public class Test {
/**
* 符号类型
*/
public static String OPERATIONALSYMBOL[] = {"+","-"};

/**
* 指定符号个数可能出现的情况list
*/
public static List<String> SYMBOLLIST = new ArrayList<String>();

public static void main(String[] args) {
test("123456789");
}

/**
* 指定任意数字字符串
* @param s
*/
public static void test(String s){
for(int i = 2;i<=s.length();i++){//最少可以把s拆成2个字符串,最多可以拆成s.length()个
loopSplitString("",s,i);
}
}
/**
* 说明:先列出所有可能的数字组合,再将每组数字进行运算
* 递归调用该方法,将str2拆成count个数字,count=1时结束递归
* @param str1      已经拆分好的部分
* @param str2      待拆分的部分
* @param count 将str2拆成count个数字
* @return
*/
public static void loopSplitString(String str1, String str2, int count){
if(count == 1){
String print = "";
String str = str1+ "," + str2;
String[] strArray = str.split(",");
symbolSituaction(strArray.length-1,"");
int calculate = 0;
for(int i = 0;i<SYMBOLLIST.size();i++){
calculate += Integer.parseInt(strArray[0]);
print += Integer.parseInt(strArray[0]);
String symbols =  SYMBOLLIST.get(i);
for(int j = 0;j<symbols.length();j++){
String symbol = symbols.substring(j, j+1);
if("+".equals(symbol)){
print+="+";
calculate += Integer.parseInt(strArray[j+1]);
}
if("-".equals(symbol)){
print+="-";
calculate -= Integer.parseInt(strArray[j+1]);
}
print+=strArray[j+1];
}
if(calculate == 100)
System.out.println(print);
print = "";
calculate = 0;
}
SYMBOLLIST = new ArrayList<String>();
return;
}
for(int cutposition = 1;cutposition < str2.length();cutposition++){
String temp1 = str2.substring(0, cutposition);
String temp2 = str2.substring(cutposition, str2.length());
loopSplitString("".equals(str1)?temp1:str1+","+temp1, temp2,count-1);
}
}
/**
* 指定符号个数可能出现的情况
* @param count  符号个数
* @param pre
*/
public static void symbolSituaction(int count ,String pre){
if(count == 0){
SYMBOLLIST.add(pre);
return;
}
for(int i=0;i<OPERATIONALSYMBOL.length;i++){
symbolSituaction(count-1,pre+OPERATIONALSYMBOL[i]);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐