当前位置: 代码迷 >> 综合 >> 华为笔试题-火星运算x#y,x$y(C++)
  详细解决方案

华为笔试题-火星运算x#y,x$y(C++)

热度:75   发布时间:2024-02-09 16:07:38.0

具体描述忘了,大概是火星有两种运算符,#和$。

其中,

x#y = 2 * x + 3 * y + 4;

x$y = 3 * x + y + 2;

$优先级高于#

输入:1#2$3$4$5#8#9,

输出:1599

代码实现:

#include <cstdio>
#include <iostream>
#include <stack>using namespace std;// # 
int xay(int x, int y) {return 2 * x + 3 * y + 4;
}// $
int xby(int x, int y) {return 3 * x + y + 2;
}int main()
{string s;cin >> s;stack<int> ds;string num;int first = -1;int second = -1;for (int i = 0; i < s.size(); i++) {if (s[i] >= '0' && s[i] <= '9') {num.push_back(s[i]);}else {if (!num.empty()) {ds.push(atoi(num.c_str()));num.erase(num.begin(), num.end());}if (first >= 0) {second = ds.top();ds.pop();ds.push(xby(first, second));first = -1;}if (s[i] == '$') {if (first < 0) {first = ds.top();ds.pop();}}}}if (!num.empty()) {ds.push(atoi(num.c_str()));if (first >= 0) {second = ds.top();ds.pop();ds.push(xby(first, second));first = -1;}}stack<int> dst;while (!ds.empty()) {dst.push(ds.top());ds.pop();}int t = -1;while (!dst.empty()) {if (t < 0) {t = dst.top();}else {t = xay(t, dst.top());}dst.pop();}cout << t;return 0;
}

 

  相关解决方案