C++判断四个正整数混合运算是否可以得到24
时间: 2023-09-28 10:11:07 浏览: 68
TwentyFour:根据给定的四个整数,逆向计算这四个整数通过什么运算可以计算出24
对于判断四个正整数混合运算是否可以得到24,可以通过遍历所有可能的运算顺序和运算符组合来进行判断。以下是一个示例的C++代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
bool isPossibleToGet24(std::vector<int>& nums) {
// Base case: if there is only one number left
if (nums.size() == 1) {
return nums[0] == 24;
}
// Try all possible pairs of two numbers
for (int i = 0; i < nums.size(); i++) {
for (int j = 0; j < nums.size(); j++) {
if (i != j) {
std::vector<int> nextNums;
for (int k = 0; k < nums.size(); k++) {
if (k != i && k != j) {
nextNums.push_back(nums[k]);
}
}
// Try all possible operations
for (char op : {'+', '-', '*', '/'}) {
if (op == '/' && nums[j] == 0) {
continue; // Avoid division by zero
}
int result;
switch (op) {
case '+':
result = nums[i] + nums[j];
break;
case '-':
result = nums[i] - nums[j];
break;
case '*':
result = nums[i] * nums[j];
break;
case '/':
result = nums[i] / nums[j];
break;
}
nextNums.push_back(result);
// Recursively check if it's possible to get 24
if (isPossibleToGet24
阅读全文