|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 zhangjinxuan 于 2022-10-15 21:07 编辑
最近在做24点计算器,计算的函数写好了,但是有一个问题,返回的表达式得从左往右计算才可得到结果24
运行实况:
- 请输入数字个数:4
- 请输入4个数字:1 2 3 4
- 此题有解,解法是:1+2+3*4
复制代码
1+2+3*4,它算出来的结果应该是15,但我想让它算出来的结果是24,就只能这样去加括号:
但仍然有问题,我该怎么去实现啊?
昨晚盯着一个算式盯了1个小时都没有想出来
如果题目还不理解,那就理解为:
给你一个表达式,在表达式中添加一些括号(不能添加多余的括号),使这个表达式与从左往右计算的表达式结果相同
样例1:
样例2:
- 输入:9-8*1*8-6/2
- 输出:(9-8)*1*(8-6)/2
复制代码
本帖最后由 dolly_yos2 于 2022-10-15 16:10 编辑
可以测试一下看看是不是这个意思(总觉得写复杂了)(假设操作数总在 int 范围内、输入总是以操作数开始、除最后一个操作数外每个操作数后总是紧接着一个四则运算符、每个四则运算符后总是紧接着一个操作数、输入中没有任何其他符号)
- #include <iostream>
- #include <vector>
- void parse_helper(
- const std::vector<int>& operands,
- const std::vector<char>& operators,
- const size_t level,
- std::ostream& output
- ){
- bool issue_parentheses = false;
- if(level > 0){
- if(!(operators.at(level) & 4u) && (operators.at(level - 1) & 4u)){
- issue_parentheses = true;
- output.put('(');
- }
- parse_helper(operands, operators, level - 1, output);
- }else{
- output << operands.at(0);
- }
- if(issue_parentheses) output.put(')');
- output.put(operators.at(level) - 1);
- output << operands.at(level + 1);
- }
- void parse(std::istream& input, std::ostream& output){
- std::vector<int> operands;
- std::vector<char> operators;
- int value;
- char op;
- input >> value;
- operands.emplace_back(value);
- while(true){
- input >> op >> value;
- if(input.eof()) break;
- operands.emplace_back(value);
- operators.emplace_back(op + 1); // 一个小小的 trick 来简化算符优先级判断
- // 考虑到 ASCII 下四则运算符的码值分别为
- // * -- 0x2A (00101010)
- // + -- 0x2B (00101011)
- // - -- 0x2D (00101101)
- // / -- 0x2F (00101111)
- // 给码值加一后可见高优先级运算符的第三低有效位(从一开始)
- // 均为 0 而低优先级的均为 1
- }
- parse_helper(operands, operators, operators.size() - 1, output);
- }
- int main(){
- parse(std::cin, std::cout);
- return 0;
- }
复制代码
|
|