✨✨个人主页:沫洺的主页
📚📚系列专栏: 📖 JavaWeb专栏📖 JavaSE专栏 📖 Java基础专栏📖vue3专栏
📖MyBatis专栏📖Spring专栏📖SpringMVC专栏📖SpringBoot专栏
📖Docker专栏📖Reids专栏📖MQ专栏📖SpringCloud专栏
💖💖如果文章对你有所帮助请留下三连✨✨
思路:先考虑输出1~9随机加减的字符串表达式,再通过正则计算字符串表达式的和,最后判断输出满足和为100的表达式。
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Expression100 {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
while (set.size()!=11){
String str = getStr();
if(sum(str)==100)
set.add(str);
}
}
for (String s: set) {
System.out.printf("%s = 100%n",s);
}
}
//计算表达式的和
public static int sum(String str){
int sum = 0;
Pattern p = Pattern.compile("[0-9]+|\\-[0-9]+");
Matcher m = p.matcher(str);
while (m.find()){
sum = sum + Integer.parseInt(m.group());
}
return sum;
}
//生成1~9随机加减的表达式
public static String getStr(){
String[] op = {"+","-",""};
StringBuilder sbu = new StringBuilder();
Random random = new Random();
for (int i = 1; i < 9; i++) {
sbu.append(i+op[random.nextInt(op.length)]);
}
sbu.append(9);
return sbu.toString();
}
}
运行结果如下
1+23-4+5+6+78-9 = 100
123+4-5+67-89 = 100
12+3-4+5+67+8+9 = 100
123-45-67+89 = 100
1+23-4+56+7+8+9 = 100
12-3-4+5-6+7+89 = 100
123-4-5-6-7+8-9 = 100
1+2+34-5+67-8+9 = 100
123+45-67+8-9 = 100
12+3+4+5-6-7+89 = 100
1+2+3-4+5+6+78+9 = 100
Process finished with exit code 0