Find 123456789 strings between 1..9 without changing the number position random +- requires the sum of the expression result to be 100, write out such an expression.

Find 123456789 strings between 1…9 without changing the number position random ± require the sum of the expression result to be 100, write this expression.

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;
}

Output result:
insert image description here

Guess you like

Origin blog.csdn.net/qq_59088934/article/details/128480948