Java有序数字序列间隔添加加减号使等式成立
2021-05-13 18:27
标签:== 数组 pattern pat sys 间隔 find out 第一个 Random rand = new Random(); Java有序数字序列间隔添加加减号使等式成立 标签:== 数组 pattern pat sys 间隔 find out 第一个 原文地址:https://www.cnblogs.com/cwj15138868532/p/13129028.html
String[] ArithmeticSign = { "+", "-", "" };
for(int n = 0;n while (true) {
String num = "1";
for (int i = 2; i int a = rand.nextInt(3) + 1;// 范围是1,2,3
num = num + ArithmeticSign[a - 1] + i;// 数组下标从0开始因为随机数里没有0所以要减1
}
int sum = 0;
Pattern p = Pattern.compile("^\\d*");//获取第一个数字
Matcher m = p.matcher(num);
while (m.find()) {
sum += Integer.parseInt(m.group());
}
p = Pattern.compile("\\+([0-9]*)");//获取正数
m = p.matcher(num);
while (m.find()) {
sum += Integer.parseInt(m.group());
}
p = Pattern.compile("\\-([0-9]*)");//获取负数
m = p.matcher(num);
while (m.find()) {
sum += Integer.parseInt(m.group());
}
if (sum == 100) {
System.out.println(num + "=" + sum);
break;
}
}
}