逆ポーランド表現
通常の式は中置式と呼ばれます。演算子は中央にあり、主に人が読むためのものです。機械で解くのは便利ではありません。
次に例を示します。3+ 5 *(2 + 6)-1
さらに、操作の順序を変更するために括弧を使用する必要がある場合がよくあります。
逆に、逆ポーランド式(接頭辞式)で表すと、上記の式は次のようになります
。-+ 3 * 5 + 2 6 1
括弧は不要で、再帰的に簡単に解くことができます。
簡単にするために、次のように仮定します
。1.3つの演算子+-*があります
。2。各オペランドは10未満の負でない整数です。
次のプログラムは、逆ポーランド表現文字列を評価します。
戻り値は配列です。最初の要素は評価結果を表し、2番目の要素は解析した文字数を表します。コードロジックを分析し、下線でコードを推測して、Webページから送信してください。
注:不足しているコードのみを回答として使用し、余分なコード、記号、説明テキストは入力しないでください。!
struct EV
{
int result; //计算结果
int n; //消耗掉的字符数
};
struct EV evaluate(char* x)
{
struct EV ev = {0,0};
struct EV v1;
struct EV v2;
if(*x==0) return ev;
if(x[0]>='0' && x[0]<='9'){
ev.result = x[0]-'0';
ev.n = 1;
return ev;
}
v1 = evaluate(x+1);
v2 = _________; //填空位置
if(x[0]=='+') ev.result = v1.result + v2.result;
if(x[0]=='*') ev.result = v1.result * v2.result;
if(x[0]=='-') ev.result = v1.result - v2.result;
ev.n = 1+v1.n+v2.n;
return ev;
}
回答:evaluate(x + v1.n + 1)
問題分析
タイトルに示されている変数に未使用の変数v1.nがあることを考えると、各ステップで与えられた結果は、特に受け取った戻り変数を考えると、有用である必要があります。次のステップでは、変数を使用します。
#include <iostream>
using namespace std;
struct EV{
int result; //计算结果
int n; //消耗掉的字符数
};
struct EV evaluate(char* x)
{
struct EV ev = {0,0};
struct EV v1;
struct EV v2;
if(*x == 0) return ev;
if(x[0]>='0' && x[0]<='9'){
ev.result = x[0] - '0'; //字符转数字
ev.n = 1;
return ev;
}
v1 = evaluate(x+1);
// v2 = _________; //填空位置
v2 = evaluate(x+v1.n+1);
if(x[0]=='+') ev.result = v1.result + v2.result;
if(x[0]=='*') ev.result = v1.result * v2.result;
if(x[0]=='-') ev.result = v1.result - v2.result;
ev.n = 1 + v1.n + v2.n;
return ev;
}
int main(int argc, char** argv) {
string str = "-+3*5+261";
const EV &ev = evaluate((char*)(str.c_str()));
cout << ev.result << endl;
return 0;
}