网易校招之表达式求值
题目描述
今天上课,老师教了小易怎么计算加法和乘法,乘法的优先级大于加法,但是如果一个运算加了括号,那么它的优先级是最高的。例如:
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
思路:对数字排序,如果第一数字是1,则前两个相加,再乘上最后一个数字
如果第一个数字不是1,则三个数字相乘
#include<bits/stdc++.h> using namespace std; int main() { vector<int> num(3); int n = 3; int i = 0; int res; while(i<3) { cin>>num[i]; i++; } sort(num.begin(),num.end()); if(num[0]==1) { res = (num[0]+num[1])*num[2]; } else{ res = num[0]*num[1]*num[2]; } cout<< res<<endl; return 0; }