求123456789 字符串1…9 之间不改数字位置随机±要求表达结果和为100,写出这样表达式。
public static void main(String[] args) {
//使用set集合输出式子
Set set=new HashSet<>();
//一共有十一个答案
while (set.size()!=11) {
String s = getString();
if (sum(s) == 100) {
set.add(s);
}
}
for (Object i:set){
System.out.println(i);
}
}
//获取拼接的字符串
public static String getString() {
StringBuilder sb1 = new StringBuilder("1");//数字1开头
Random r1 = new Random();//随机
String[] s1 = {
"-", "+", ""};//随机加减
for (int i = 2; i <=9; i++) {
sb1.append(s1[r1.nextInt(s1.length)]);
sb1.append(i);
}
return sb1.toString();
}
//使用正则表达式数字求和
public static int sum(String s1) {
Pattern p1 = Pattern.compile("-?\\d+");
Matcher m1 = p1.matcher(s1);
int sum = 0;
while (m1.find()) {
int n = Integer.parseInt(m1.group());
sum += n;
}
return sum;
}
输出结果: