C++ 表达式求值

题目描述

今天上课,老师教了小易怎么计算加法和乘法,乘法的优先级大于加法,但是如果一个运算加了括号,那么它的优先级是最高的。例如:

1+2*3=7
1*(2+3)=5
1*2*3=6
(1+2)*3=9

现在小易希望你帮他计算给定3个数a,b,c,在它们中间添加"+", "*", "(", ")"符号,能够获得的最大值。

输入描述:

一行三个数a,b,c (1 <= a, b, c <= 10)

输出描述:

能够获得的最大值

示例1

输入

复制

1 2 3

输出

复制

9

 

ac代码如下(贪心即可)

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int main()
{
	vector<int> num;
	for (int i = 0; i < 3; i++)
	{
		int a;
		cin >> a;
		num.push_back(a);
	}
	vector<int> results;
	for (int i = 0; i < 4; i++)
	{
		if (i == 0)
		{
			results.push_back(num[0] * num[1] * num[2]);
		}
		else if (i == 1)
		{
			results.push_back((num[0] + num[1])*num[2]);
		}
		else if (i == 2)
		{
			results.push_back(num[0] * (num[1] + num[2]));
		}
		else if (i == 3)
		{
			results.push_back(num[0] + num[1] + num[2]);
		}
	}
	vector<int>::iterator maxIter = max_element(begin(results), end(results));
	cout << *maxIter << endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值