Content is user-generated and unverified.
#include <iostream> #include <string> #include <stack> #include <cctype> using namespace std; // Function to get precedence of operators int precedence(char op) { if (op == '+' || op == '-') return 1; if (op == '*' || op == '/') return 2; return 0; } // Function to perform arithmetic operation int applyOperation(int a, int b, char op) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } return 0; } // Function to evaluate mathematical expression using BODMAS int evaluateExpression(string expr) { stack<int> values; stack<char> operators; for (size_t i = 0; i < expr.length(); i++) { if (isdigit(expr[i])) { // Parse the number int num = 0; while (i < expr.length() && isdigit(expr[i])) { num = num * 10 + (expr[i] - '0'); i++; } i--; // Adjust for the extra increment in loop values.push(num); } else if (expr[i] == '+' || expr[i] == '-' || expr[i] == '*' || expr[i] == '/') { // Process operators based on precedence while (!operators.empty() && precedence(operators.top()) >= precedence(expr[i])) { int b = values.top(); values.pop(); int a = values.top(); values.pop(); char op = operators.top(); operators.pop(); values.push(applyOperation(a, b, op)); } operators.push(expr[i]); } } // Apply remaining operations while (!operators.empty()) { int b = values.top(); values.pop(); int a = values.top(); values.pop(); char op = operators.top(); operators.pop(); values.push(applyOperation(a, b, op)); } return values.top(); } // Function to process the input string string processString(string s) { string result = ""; size_t i = 0; while (i < s.length()) { if (isdigit(s[i])) { // It's a digit, collect the entire number while (i < s.length() && isdigit(s[i])) { result += s[i]; i++; } // Skip any alphabets that follow this number while (i < s.length() && isalpha(s[i])) { i++; } } else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') { // It's an operator result += s[i]; i++; // Check if next characters are only alphabets (standalone variable) if (i < s.length() && isalpha(s[i])) { // Skip all alphabets and add '1' for standalone variable while (i < s.length() && isalpha(s[i])) { i++; } result += "1"; } } else if (isalpha(s[i])) { // Standalone alphabets at the beginning or after processing result += "1"; while (i < s.length() && isalpha(s[i])) { i++; } } else { i++; } } // Handle case where string starts with alphabets if (result.empty()) { result = "1"; } return result; } int main() { string input; cin >> input; // Process the string to remove alphabets and handle coefficients string cleanExpr = processString(input); // Evaluate the expression using BODMAS int result = evaluateExpression(cleanExpr); cout << result << endl; return 0; }
Content is user-generated and unverified.
    Mathematical Expression Evaluator | Claude