20火星文计算

1 题目描述

/*
 * 已知火星人使用的运算符为 # $, 其与地球人的等价公式如下:
 * x#y = 2*x + 3*y + 4
 * x$y = 3*x + y + 2
 *
 * 1 其中 x y 是无符号整数
 * 2 地球人公式按c语言规则计算
 * 3 火星人公式中, $ 的优先级高于 # , 想通的运算符,按从左到右的顺序计算
 *
输入
7#6$5#12


输出
226


 * */

2 代码1 递归


#include "string"
#include "iostream"
#include "vector"
using namespace std;

// 7#6$5#12
int getResult(string str) {
  if (str.find('#') != string::npos) {
    int id = str.rfind('#');     // 这里的重点是,要从rfind, 为什么呢,因为最终的相同优先级要从左向右计算,
    string left = str.substr(0, id - 0); // 所以要保持左边的的地柜分支比右边深,才能保证左边的数字,先回溯出来,进行计算
    string right = str.substr(id+1);
    return 2*getResult(left) + 3*getResult(right) + 4;
  }

  if (str.find('$') != string::npos) {  // 这里保证 $ 优先级高
    int id = str.rfind('$');   // 这里的重点是,要从rfind
    string left = str.substr(0, id - 0);
    string right = str.substr(id+1);
    return 3*getResult(left) + getResult(right) + 2;
  }

  return stoi(str);
}

int main() {
  string str;
  getline(cin, str);

  int ret = getResult(str);

  cout << ret << endl;
  return 0;
}

3 代码2 栈


#include "string"
#include "iostream"
#include "vector"
using namespace std;

// x#y
int op1(int x, int y) {
  return 2*x + 3*y + 4;
}

// x$y    高优先级
int op2(int x, int y) {
  return 3*x + y + 2;
}
// 7#6$5#12
int getResult(string str) {
  vector<int> st;
  int left = 0;
  char curOp;

  for (int i = 0; i < str.size(); i++) {
    int num = 0;
    if (i == str.size()-1) {
      num = stoi(str.substr(left, i - left+1)) ; // 获取一个数字
      if (curOp == '#' || st.empty()) {
        st.push_back(num);
      } else if (curOp == '$') {
        int numt = op2(st.back(), num);
        st[st.size()-1] = numt;
      }
      break;
    } else {
      if (str[i] == '#' || str[i] == '$') {
        num = stoi(str.substr(left, i - left)) ; // 获取一个数字
        if (curOp == '#' || st.empty()) { // 优先级低,入栈
          st.push_back(num);
        } else if (curOp == '$') { // 优先级高,直接计算
          int numt = op2(st.back(), num);
          st[st.size()-1] = numt;
        }
        curOp = str[i]; // 更新curOp

        left = i+1;
      }
    }
  }

  int ans = st[0];
  for (int i = 1; i < st.size(); i++) {
    ans = op1(ans, st[i]);
  }
  return ans;
}

int main() {
  string str;
  getline(cin, str);

  int ret = getResult(str);

  cout << ret << endl;
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值