华为OJ 初级:24点游戏算法

描述

问题描述:给出4个1-10的数字,通过加减乘除,得到数字为24就算胜利
输入:
4个1-10的数字。[数字允许重复,测试用例保证无异常数字]
输出:
true or false

知识点 循环
运行时间限制 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;
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值