给定一个字符串描述的算术表达式,计算出结果值。
输入字符串长度不超过 100 ,合法的字符包括 ”+, -, *, /, (, )” , ”0-9” 。
数据范围:运算过程中和最终结果均满足
,即只进行整型运算,确保输入的表达式合法
/** * 字符串预处理 * 中缀表达式转后缀表达式 * 后缀表达式计算 */
//思路:
//1.字符串预处理,针对可能出现的“{,},[,],-”等特殊情况进行替换,判断‘-’是负号还是减号,负号前面+0,转变成减法运算
//2.将中缀字符串转变为后缀字符串数组
//3.对后缀字符串数组进行求解
#include<iostream>
#include<vector>
#include<string>
#include<stack>
#include<sstream>
using namespace std;
bool cmpPriority(char top,char cur)//比较当前字符与栈顶字符的优先级,若栈顶高,返回true
{
if((top=='+' || top=='-') && (cur=='+' || cur=='-'))
return true;
if((top=='*' || top=='/') && (cur=='+' || cur=='-'|| top=='*' || top=='/'))
return true;
if(cur==')')
return true;
return false;
}
void preProcess(string &str)//对字符串进行预处理
{
for(int i=0;i<str.size();++i)
{
if(str[i]=='{')//将‘{、}、[,]’替换成'()'
str[i]='(';
else if(str[i]=='}')
str[i]=')';
else if(str[i]=='[')
str[i]='(';
else if(str[i]==']')
str[i]=')';
else if(str[i]=='-')
{
if(i==0)//将'-'前面添加0转变成减法运算
str.insert(0,1,'0');
else if(str[i-1]=='(')
str.insert(i,1,'0');
}
}
}
vector<string> mid2post(string &str)
{
vector<string>vstr;
stack<char>cstack;
for(int i=0;i<str.size();++i)//扫描字符串
{
string temp="";
if(str[i]>='0' && str[i]<='9')//若是数字
{
temp+=str[i];
while(i+1<str.size() && str[i+1]>='0' && str[i+1]<='9')
{
temp+=str[i+1];//若是连续数字
++i;
}
vstr.push_back(temp);
}
else if(cstack.empty() || str[i]=='(')//若栈空或者字符为'('
cstack.push(str[i]);
else if(cmpPriority(cstack.top(),str[i]))//若栈顶元素优先级较高,栈顶元素出栈
{
if(str[i]==')')//若当前字符是右括号,栈中元素出栈,入字符串数组中,直到遇到'('
{
while(!cstack.empty() && cstack.top()!='(')
{
temp+=cstack.top();
cstack.pop();
vstr.push_back(temp);
temp="";
}
cstack.pop();
}
else//栈中优先级高的元素出栈,入字符串数组,直到优先级低于当前字符
{
while(!cstack.empty() && cmpPriority(cstack.top(),str[i]))
{
temp+=cstack.top();
cstack.pop();
vstr.push_back(temp);
temp="";
}
cstack.push(str[i]);
}
}
else//当前字符优先级高于栈顶元素,直接入栈
cstack.push(str[i]);
}
while(!cstack.empty())//栈中还存在运算符时,出栈,存入字符串数组
{
string temp="";
temp+=cstack.top();
cstack.pop();
vstr.push_back(temp);
}
return vstr;
}
int calcPostExp(vector<string> & vstr)//对后缀表达式进行求值,主要是根据运算符取出两个操作数进行运算
{
int num,op1,op2;
stack<int>opstack;
for(int i=0;i<vstr.size();++i)
{
string temp=vstr[i];
if(temp[0]>='0' && temp[0]<='9')//如果当前字符串是数字,利用字符串流转化为int型
{
stringstream ss;
ss<<temp;
ss>>num;
opstack.push(num);
}
else if(vstr[i]=="+")//若是操作符,取出两个操作数,进行运算,并将结果存入
{
op2=opstack.top();
opstack.pop();
op1=opstack.top();
opstack.pop();
opstack.push(op1+op2);
}
else if(vstr[i]=="-")
{
op2=opstack.top();
opstack.pop();
op1=opstack.top();
opstack.pop();
opstack.push(op1-op2);
}
else if(vstr[i]=="*")
{
op2=opstack.top();
opstack.pop();
op1=opstack.top();
opstack.pop();
opstack.push(op1*op2);
}
else if(vstr[i]=="/")
{
op2=opstack.top();
opstack.pop();
op1=opstack.top();
opstack.pop();
opstack.push(op1/op2);
}
}
return opstack.top();//最终的栈顶元素就是求解的结果
}
void calcExp(string str)
{
vector<string>vstr;
preProcess(str);//对字符串进行预处理
vstr=mid2post(str);//将中缀表达式转为后缀,保存在字符串数组中,方便下一步求解
int res=calcPostExp(vstr);
cout<<res<<endl;
}
int main()
{
string str;
while(getline(cin,str))
{
calcExp(str);
}
return 0;
}
"""
题目说表达式合法性由做题者检查,并非程序检查,所以简单问题简单处理
while True:
try:
raw_str = input()
valid_str = '+-*/()0123456789'
if len(raw_str) > 100:
print("Input exceeds maximum length")
else:
for i in raw_str:
if i not in valid_str:
print("Input contains invalid string")
print(eval(raw_str))
except:
break
"""
print(eval(input())) import java.util.*;
import javax.script.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn");
System.out.println(scriptEngine.eval(input));
}
} import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Scanner;
public class Main
{
public static void main(String args[]) {
String enter;
Scanner in = new Scanner(System.in);
while (in.hasNextLine()){
enter = in.nextLine();
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
try {
Object result = engine.eval(enter);
System.out.println(result);
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
} import java.util.*;
import javax.script.*;
public class Main{
public static void main(String[] args) throws ScriptException {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn");
System.out.println(scriptEngine.eval(input));
}
} #include <iostream>
#include <string>
#include <stack>
using namespace std;
stack<int> nums;
stack<char> sig;
int core(int num1,int num2,char sig)
{
if(sig=='+')
return num1+num2;
if(sig=='-')
return num2-num1;
if(sig=='*')
return num1*num2;
else if(num1!=0)
return num2/num1;
return -1;
}
void calc()
{
int num1=nums.top();
nums.pop();
int num2=nums.top();
nums.pop();
char c=sig.top();
sig.pop();
nums.push(core(num1,num2,c));
}
int main()
{
string s;
while(cin>>s)
{
int l=s.length();
for(int i=0;i<l;i++)
{
if(s[i]>='0'&&s[i]<='9')
{
int j=i+1;
int temp=s[i]-48;
while(j<l&&s[j]>='0'&&s[j]<='9')
temp=temp*10+(s[j++]-48);
nums.push(temp);
i=--j;
}
else
{
if(sig.empty()||s[i]=='(')
{
sig.push(s[i]);
continue;
}
else if(s[i]=='+'||s[i]=='-')
{
while(!sig.empty()&&sig.top()!='(')
calc();
sig.push(s[i]);
}
else if(s[i]=='*'||s[i]=='/')
{
while(!sig.empty()&&(sig.top()=='*'||sig.top()=='/'))
calc();
sig.push(s[i]);
}
else if(s[i]==')')
{
while(!sig.empty()&&sig.top()!='(')
calc();
sig.pop();
}
}
}
while(!sig.empty())
calc();
cout<<nums.top()<<endl;
nums.pop();
}
}
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 优先级maps
HashMap<Character, Integer> maps = new HashMap<>();
maps.put('+', 1);
maps.put('-', 1);
maps.put('*', 2);
maps.put('/', 2);
maps.put('%', 2);
maps.put('^', 3);
String str = "";
while ((str = br.readLine()) != null) {
// 双栈法
// 数据栈
Deque<Integer> nums = new LinkedList<>();
nums.push(0);
// 操作栈
Deque<Character> ops = new LinkedList<>();
// 预处理
str = str.replaceAll(" ", "");
str = str.replaceAll("\\(-", "\\(0-");
str = str.replaceAll("\\(+", "\\(0+");
if (str.charAt(0) == '-') { // 特判首字符是负数
str = '0' + str;
}
// 转换成字符数组
char[] chars = str.toCharArray();
int n = str.length();
for(int i = 0; i < n; i++) {
if (chars[i] == '(') {
ops.push(chars[i]);
} else if (chars[i] == ')') {
while(!ops.isEmpty()) {
if (ops.peek() == '(') {
ops.pop();
break;
} else {
calc(nums, ops);
}
}
} else {
if (isNumber(chars[i])) {
// 当前遇到的是数字
int j = 0;
int k = i;
while(k < n && isNumber(chars[k])) {
j = j * 10 + (chars[k] - '0');
k++;
}
nums.push(j);
i = k - 1;
} else {
// 当前遇到的是加减乘除
while (!ops.isEmpty() && ops.peek() != '(') {
if (maps.get(ops.peek()) >= maps.get(chars[i])) {
calc(nums, ops);
} else {
break;
}
}
ops.push(chars[i]);
}
}
}
while (!ops.isEmpty() && ops.peek() != '(') {
calc(nums, ops);
}
System.out.println(nums.peek());
}
}
// 判断是否是数字
public static boolean isNumber(char cur) {
return Character.isDigit(cur);
}
// 进行计算
public static void calc(Deque<Integer> nums, Deque<Character> ops) {
if (ops.isEmpty()) return;
if (nums.isEmpty() || nums.size() < 2) return;
int b = nums.pop();
int a = nums.pop();
int op = ops.pop();
int res = 0;
if (op == '+') {
res = a + b;
} else if (op == '-') {
res = a - b;
} else if (op == '*') {
res = a * b;
} else if (op == '/') {
res = a / b;
} else if (op == '^') {
res = (int)Math.pow(a, b);
} else if (op == '%') {
res = a % b;
}
nums.push(res);
}
} const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void async function () {
// Write your code here
while(line = await readline()){
// console.log(eval(line))
console.log(Function(`return ${line}`)())
}
}()
#include <iostream>
#include <string>
#include <stack>
#include <vector>
using namespace std;
int main() {
string expre;
while (cin >> expre) {
vector<char> exp;
stack<char> op;
// 3-10+(0+(10+5+3)-10)
// 3 10 - 0 10 5 + 3 + + 10 - +
for (size_t i = 0; i < expre.length(); i++) {
if (expre[i] >= '0' && expre[i] <= '9') {
if (i > 0 && expre[i - 1] >= '0' && expre[i - 1] <= '9') {
int tmp = exp.back() - '0';
tmp = tmp * 10 + expre[i];
exp.pop_back();
exp.push_back(tmp);
} else {
exp.push_back(expre[i]);
}
} else if (expre[i] == ')') {
while (!op.empty() && op.top() != '(') {
exp.push_back(op.top());
op.pop();
}
op.pop();
}
else if (expre[i] == '-' || expre[i] == '+') {
if (expre[i] == '-') {
if (i == 0 || expre[i - 1] == '(') {
exp.push_back('0');
}
}
while (!op.empty() && (op.top() == '+' || op.top() == '-' || op.top() == '*' || op.top() == '/')) {
exp.push_back(op.top());
op.pop();
}
op.push(expre[i]);
} else if (expre[i] == '*' || expre[i] == '/') {
while (!op.empty() && (op.top() == '*' || op.top() == '/')) {
exp.push_back(op.top());
op.pop();
}
op.push(expre[i]);
} else {
op.push(expre[i]);
}
}
while (!op.empty()) {
exp.push_back(op.top());
op.pop();
}
stack<int> res;
for (size_t i = 0; i < exp.size(); i++) {
if (exp[i] == '+' || exp[i] == '-' || exp[i] == '*' || exp[i] == '/') {
int val1 = res.top();
res.pop();
int val2 = res.top();
res.pop();
int tmp;
if (exp[i] == '+') {
tmp = val2 + val1;
} else if (exp[i] == '-') {
tmp = val2 - val1;
} else if (exp[i] == '*') {
tmp = val2 * val1;
} else if (exp[i] == '/'){
tmp = val2 / val1;
}
res.push(tmp);
} else {
res.push(exp[i] - '0');
}
}
cout << res.top() << endl;
}
return 0;
}
给定一个字符串描述的算术表达式,计算出结果值。
输入算术表达式
计算出结果值
400+5复制
405
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
/**
无视左括号
将操作数压入操作数栈
将运算符压入运算符栈
在遇到右括号的时候,从运算符栈中弹出一个运算符,再从操作数栈中弹出所需的操作数,
并且将运算结果压入操作数栈中
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Stack<Integer> s1 = new Stack<>(); //操作数栈
Stack<Character> s2 = new Stack<>(); //运算符栈
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String str = in.nextLine();
int len = str.length();
String tem = "";
for(int i=0; i<len; i++) {
char ch = str.charAt(i);
switch(ch) {
case '(':
case '[':
case '{':
break; //忽略
case '+':
case '-':
case '*':
case '/':
s2.push(ch);//操作符入栈
break;
case ')':
case ']':
case '}':
//计算,并将操作数重新入栈
//1.弹出操作符
//2.弹出操作数1
//3.弹出操作数2
//计算,并将结果重新放到操作数栈
char flag = s2.pop();
Integer num1 = s1.pop();
Integer num2 = s1.pop();
Integer sum = null;
switch(flag) {
case '+':
sum = num1 + num2;
s1.push(sum);
break;
case '-':
sum = num1 - num2;
s1.push(sum);
break;
case '*':
sum = num1 * num2;
s1.push(sum);
break;
case '/':
sum = num1 / num2;
s1.push(sum);
break;
}
break;
default:
tem += String.valueOf(ch);
if(!nextIsNotNum(str, i, len)) {
s1.push(Integer.parseInt(tem));
tem = "";
}
break;
}
}
//统计并输出
int res = 0;
while(!s1.isEmpty()) {
res += s1.pop();
}
System.out.println(res);
}
}
public static boolean nextIsNotNum(String str, int n, int len) {
int temp = -1;
try {
temp = Integer.parseInt(String.valueOf(str.charAt(n+1)));
} catch(Exception e) {
temp = -1;
}
return temp != -1;
}
} import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
System.out.println(culSuffix(infixToSuffix(sc.nextLine())));
}
}
// 中缀表达式 转 后缀表达式
public static List<String> infixToSuffix(String str) {
List<String> result = new ArrayList<>();
Stack<Character> operateStack = new Stack<>();
boolean flag = true;
String temp = "";
for (char c : str.toCharArray()) {
// 负数开头处理(补零)
if (flag && c == '-') {
result.add("0");
}
flag = false;
// 多位数处理
if (c >= '0' && c <= '9') {
temp += c;
continue;
}
// 数字入栈(集合)
if (temp.length() > 0) {
result.add(temp);
temp = "";
}
// 符号入栈(集合)
if (operateStack.empty() || operateStack.peek() == '(') {
operateStack.push(c);
} else if (c == '(') {
operateStack.push(c);
flag = true;
} else if (c == ')'){
while (operateStack.peek() != '(') {
result.add(operateStack.pop() + "");
}
operateStack.pop();
} else {
while (!operateStack.empty()
&& operateStack.peek() != '('
&& getPriority(c) <= getPriority(operateStack.peek())) {
result.add(operateStack.pop() + "");
}
operateStack.push(c);
}
}
// 后续处理
if (temp.length() > 0) {
result.add(temp);
}
while (!operateStack.empty()) {
result.add(operateStack.pop() + "");
}
return result;
}
// 获取操作符优先级
public static int getPriority(char c) {
if (c == '+' || c == '-') {
return 1;
}
if (c == '*' || c == '/') {
return 2;
}
throw new RuntimeException("异常操作符!");
}
// 计算后缀表达式
public static int culSuffix(List<String> list) {
Stack<Integer> numStack = new Stack<>();
Stack<String> operateStack = new Stack<>();
Integer temp = null;
for (String item : list) {
switch (item) {
case "+" :
case "-" :
case "*" :
case "/" :
temp = cul(numStack.pop(), numStack.pop(), item);
numStack.push(temp);
break;
default :
numStack.push(Integer.parseInt(item));
}
}
return numStack.peek();
}
// 计算加 减 乘 除
public static int cul(int num1, int num2, String operate) {
switch (operate) {
case "+" :
return num2 + num1;
case "-" :
return num2 - num1;
case "*" :
return num2 * num1;
case "/" :
return num2 / num1;
}
throw new RuntimeException("异常数据,计算失败!");
}
}