描述 | |
---|---|
知识点 | 循环 |
运行时间限制 | 10M |
内存限制 | 128 |
输入 | 输入4个int整数 |
输出 | 返回能否得到24点,能输出true,不能输出false |
样例输入 | 7 2 1 10 |
样例输出 | true |
/*本题使用递归的方法
* */
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] nums = new int[4];
for (int i = 0; i < 4; i++)
nums[i] = sc.nextInt();
sc.close();
System.out.println(getResult(nums, 0, 0));
}
private static boolean getResult(int[] nums, int i, int result) {
if (result == 24)
return true;
if (i < 4) {
//加减乘除四种运算,只要其中一种返回true则运算结束,当result=0时,乘除的运算直接返回0
return getResult(nums, i + 1, result + nums[i])
|| getResult(nums, i + 1, result - nums[i])
|| getResult(nums, i + 1, result == 0 ? 0 : result
* nums[i])
|| getResult(nums, i + 1, result == 0 ? 0 : result
/ nums[i]);
} else
return false;
}
}