📜  评估简单表达式的程序

📅  最后修改于: 2021-04-23 20:32:42             🧑  作者: Mango

您将得到一个代表数字和操作数表达式的字符串。例如1 + 2 * 3、1-2 + 4。您需要评估字符串或表达式。不遵循BODMAS。如果表达式语法错误,则返回-1。
测试用例:
a)1 + 2 * 3将被评估为9。
b)4-2 + 6 * 3将计算为24。
c)1 ++ 2将被评估为-1(INVALID)。
同样,在字符串可能会出现空格。在这种情况下,我们需要忽略空格。像:-1 * 2 -1等于1。

资料来源:亚马逊访谈问题

强烈建议最小化浏览器,然后自己尝试。
这个想法很简单,从第一个字符开始,然后从左向右遍历,并检查是否有错误,例如两个连续的运算符和操作数。我们还跟踪结果并在遍历表达式时更新结果。

以下是评估给定表达式的程序。

C++
// C++ program to evaluate a given expression
#include 
using namespace std;
  
// A utility function to check if a given character is operand
bool isOperand(char c) { return (c >= '0' && c <= '9'); }
  
// utility function to find value of and operand
int value(char c) {  return (c - '0'); }
  
// This function evaluates simple expressions. It returns -1 if the
// given expression is invalid.
int evaluate(char *exp)
{
    // Base Case: Given expression is empty
    if (*exp == '\0')  return -1;
  
    // The first character must be an operand, find its value
    int res = value(exp[0]);
  
    // Traverse the remaining characters in pairs
    for (int i = 1; exp[i]; i += 2)
    {
        // The next character must be an operator, and
        // next to next an operand
        char opr = exp[i], opd = exp[i+1];
  
        // If next to next character is not an operand
        if (!isOperand(opd))  return -1;
  
        // Update result according to the operator
        if (opr == '+')       res += value(opd);
        else if (opr == '-')  res -= value(opd);
        else if (opr == '*')  res *= value(opd);
        else if (opr == '/')  res /= value(opd);
  
        // If not a valid operator
        else                  return -1;
    }
    return res;
}
  
// Driver program to test above function
int main()
{
    char expr1[] = "1+2*5+3";
    int res = evaluate(expr1);
    (res == -1)? cout << expr1 << " is " << "Invalid\n":
                 cout << "Value of " << expr1 << " is " << res << endl;
  
    char expr2[] = "1+2*3";
    res = evaluate(expr2);
    (res == -1)? cout << expr2 << " is " << "Invalid\n":
                 cout << "Value of " << expr2 << " is " << res << endl;
  
    char expr3[] = "4-2+6*3";
    res = evaluate(expr3);
    (res == -1)? cout << expr3 << " is " << "Invalid\n":
                 cout << "Value of " << expr3 << " is " << res << endl;
  
    char expr4[] = "1++2";
    res = evaluate(expr4);
    (res == -1)? cout << expr4 << " is " << "Invalid\n":
                 cout << "Value of " << expr4 << " is " << res << endl;
    return 0;
}


Java
// Java program to evaluate a given expression 
  
class GFG{
// A utility function to check if 
// a given character is operand 
static boolean isOperand(char c) 
{ 
    return (c >= '0' && c <= '9'); 
      
} 
  
// utility function to find value of and operand 
static int value(char c)
{ 
    return (int)(c - '0');
      
} 
  
// This function evaluates simple expressions. 
// It returns -1 if the given 
// expression is invalid. 
static int evaluate(String exp) 
{ 
    // Base Case: Given expression is empty 
    if (exp.length() == 0) return -1; 
  
    // The first character must be 
    // an operand, find its value 
    int res = value(exp.charAt(0)); 
  
    // Traverse the remaining characters in pairs 
    for (int i = 1; i


Python3
# Python3 program to evaluate a
# given expression
  
# A utility function to check if
# a given character is operand
def isOperand(c): 
   
    return (c >= '0' and c <= '9'); 
  
# utility function to find
# value of and operand
def value(c): 
    return ord(c) - ord('0'); 
  
# This function evaluates simple
# expressions. It returns -1 if the
# given expression is invalid.
def evaluate(exp):
  
    len1 = len(exp);
      
    # Base Case: Given expression is empty
    if (len1 == 0):
        return -1;
  
    # The first character must be 
    # an operand, find its value
    res = value(exp[0]);
  
    # Traverse the remaining
    # characters in pairs
    for i in range(1,len1,2):
        # The next character must be 
        # an operator, and next to 
        # next an operand
        opr = exp[i];
        opd = exp[i + 1];
  
        # If next to next character 
        # is not an operand
        if (isOperand(opd)==False):
            return -1;
  
        # Update result according 
        # to the operator
        if (opr == '+'):
            res += value(opd);
        elif (opr == '-'):
            res -= int(value(opd));
        elif (opr == '*'):
            res *= int(value(opd));
        elif (opr == '/'):
            res /= int(value(opd));
  
        # If not a valid operator
        else:
            return -1;
      
    return res;
  
# Driver Code
expr1 = "1+2*5+3";
res = evaluate(expr1);
print(expr1,"is Invalid") if (res == -1) else print("Value of",expr1,"is",res);
  
expr2 = "1+2*3";
res = evaluate(expr2);
print(expr2,"is Invalid") if (res == -1) else print("Value of",expr2,"is",res);
  
expr3 = "4-2+6*3";
res = evaluate(expr3);
print(expr3,"is Invalid") if (res == -1) else print("Value of",expr3,"is",res);
  
expr4 = "1++2";
res = evaluate(expr4);
print(expr4,"is Invalid") if (res == -1) else print("Value of",expr4,"is",res);
  
# This code is contributed by mits


C#
// C# program to evaluate a given expression 
using System;
class GFG{
      
// A utility function to check if
// a given character is operand 
static bool isOperand(char c) { 
    return (c >= '0' && c <= '9'); 
      
} 
  
// utility function to find value of and operand 
static int value(char c) { return (int)(c - '0'); } 
  
// This function evaluates simple 
// expressions. It returns -1 if the 
// given expression is invalid. 
static int evaluate(string exp) 
{ 
    // Base Case: Given expression is empty 
    if (exp.Length == 0) return -1; 
  
    // The first character must be
    // an operand, find its value 
    int res = value(exp[0]); 
  
    // Traverse the remaining characters in pairs 
    for (int i = 1; i


PHP
= '0' && $c <= '9'); 
}
  
// utility function to find
// value of and operand
function value($c) 
{ 
    return ($c - '0'); 
}
  
// This function evaluates simple
// expressions. It returns -1 if the
// given expression is invalid.
function evaluate($exp)
{
    $len = strlen($exp);
      
    // Base Case: Given expression is empty
    if ($len == 0) return -1;
  
    // The first character must be 
    // an operand, find its value
    $res = (int)(value($exp[0]));
  
    // Traverse the remaining
    // characters in pairs
    for ($i = 1; $i < $len; $i += 2)
    {
        // The next character must be  
        // an operator, and next to 
        // next an operand
        $opr = $exp[$i];
        $opd = $exp[$i + 1];
  
        // If next to next character 
        // is not an operand
        if (!isOperand($opd)) 
        return -1;
  
        // Update result according 
        // to the operator
        if ($opr == '+')     
        $res += value($opd);
        else if ($opr == '-') 
            $res -= (int)(value($opd));
        else if ($opr == '*') 
            $res *= (int)(value($opd));
        else if ($opr == '/') 
            $res /= (int)(value($opd));
  
        // If not a valid operator
        else                
        return -1;
    }
    return $res;
}
  
// Driver Code
$expr1 = "1+2*5+3";
$res = evaluate($expr1);
($res == -1) ? print($expr1." is Invalid\n"):
               print("Value of " . $expr1 . 
                     " is " . $res . "\n");
              
$expr2 = "1+2*3";
$res = evaluate($expr2);
($res == -1) ? print($expr2." is Invalid\n"):
               print("Value of " . $expr2 . 
                     " is " . $res . "\n");
              
$expr3 = "4-2+6*3";
$res = evaluate($expr3);
($res == -1) ? print($expr3." is Invalid\n"):
               print("Value of " . $expr3 . 
                     " is " . $res . "\n");
              
$expr4 = "1++2";
$res = evaluate($expr4);
($res == -1) ? print($expr4." is Invalid\n"):
               print("Value of " . $expr4 .
                     " is " . $res . "\n");
  
// This code is contributed by mits
?>


输出:

Value of 1+2*5+3 is 18
Value of 1+2*3 is 9
Value of 4-2+6*3 is 24
1++2 is Invalid

上面的代码不处理空格。我们可以通过首先删除给定字符串的所有空格来处理空格。更好的解决方案是处理单个遍历中的空间。这留作练习。

时间复杂度为O(n),其中n是给定表达式的长度。