java牛客网四则运算_四则运算

待我称王封你为后i 2022-11-06 05:44 138阅读 0赞

1

//用python做(两句话),显然得不到练习的效果,有什么意思呢;

//还是用C++写吧。

#include

#include

#include

#include

using namespace std;

bool isHigh(char top_op,char InfixExp_op)

//判断操作符的优先级;

//top_op为栈顶操作符

//InfixExp_op为当前读入操作符

//如果栈顶操作符优先级高,则弹出栈顶操作符;

//如果栈顶操作符优先级低,则压入当前读入操作符;

{

if ((top_op== ‘+’)&&(InfixExp_op== ‘+’)) return true;

if ((top_op== ‘+’)&&(InfixExp_op== ‘-‘)) return true;

if ((top_op== ‘-‘)&&(InfixExp_op== ‘+’)) return true;

if ((top_op== ‘-‘)&&(InfixExp_op== ‘-‘)) return true;

if ((top_op== ‘*‘)&&(InfixExp_op== ‘+’)) return true;

if ((top_op== ‘*‘)&&(InfixExp_op== ‘-‘)) return true;

if ((top_op== ‘*‘)&&(InfixExp_op== ‘*‘)) return true;

if ((top_op== ‘*‘)&&(InfixExp_op== ‘/‘)) return true;

if ((top_op== ‘/‘)&&(InfixExp_op== ‘+’)) return true;

if ((top_op== ‘/‘)&&(InfixExp_op== ‘-‘)) return true;

if ((top_op== ‘/‘)&&(InfixExp_op== ‘*‘)) return true;

if ((top_op== ‘/‘)&&(InfixExp_op== ‘/‘)) return true;

if (InfixExp_op== ‘)’) return true;

return false;

}

int main()

{

char str[5000];

while(cin>>str)

{

int len=strlen(str);

stack sta;

vector vec;

vector vec_b;

int sum=0;

int flag=1;

int flb=0;//两个相邻的数之间运算符的个数,挑负数;

for(int i=0;i

{

if(i==0&&str[i]==’-‘)//把负号挑出来;

{

flag=-1;

continue;

}

if(i>0&&str[i]==’-‘&&flb==1)//把负号挑出来;

{

flag=-1;

continue;

}

if(str[i]>=’0’&&str[i]<=’9’)

{

sum=sum*10+(str[i]-‘0’);

if(!(str[i+1]>=’0’&&str[i+1]<=’9’))

{

sum*=flag;

vec.push_back(sum);

vec_b.push_back(true);//真为数,假为运算符的;

sum=0;

flag=1;

flb=0;

}

}

else

{

if(str[i]==’[‘||str[i]==’{‘)

str[i]=’(‘;

if(str[i]==’]‘||str[i]==’}‘)

str[i]=’)’;

if(str[i]==’+’||str[i]==’-‘||str[i]==’*‘||str[i]==’/‘)

++flb;

if (sta.empty())

//栈为空,压入操作符;

sta.push(str[i]);

else if(isHigh(sta.top(),str[i]))

//栈顶操作符优先,比如栈顶为*,当前操作符为+,则弹出*

{

if (str[i]!= ‘)’)

//非闭括号;

//弹出栈中操作符直到栈顶操作数优先级低于当前读入操作数;

//压入当前读入操作符;

{

do

{

if(sta.top()!=’(‘||sta.top()!=’)’)

{

vec.push_back(sta.top());

vec_b.push_back(false);

}

sta.pop();

}while((!sta.empty())&&(isHigh(sta.top(),str[i])));

sta.push(str[i]);

}

else

//闭括号;

{

while((!sta.empty())&&(sta.top()!= ‘(‘))

//弹出直到开括号;

{

if(sta.top()!=’(‘||sta.top()!=’)’)

{

vec.push_back(sta.top());

vec_b.push_back(false);

}

sta.pop();

}

if ((!sta.empty())&&(sta.top()== ‘(‘))

sta.pop();

//弹出开括号;

}

}

else if(!isHigh(sta.top(),str[i]))

//中缀表达式中操作符优先;

//比如栈顶为+,而当前读入*;

{

sta.push(str[i]);

//压入当前读入操作符;

}

}

}

while(!sta.empty())

//把栈中剩余的操作符依次弹出;

{

if(sta.top()!=’(‘||sta.top()!=’)’)

{

vec.push_back(sta.top());

vec_b.push_back(false);

}

sta.pop();

}

while(!sta.empty())

sta.pop();

stack sta_i;

int mm=vec.size();

int res=0;

/*for (int i=0;i

{

if (vec_b[i])

{

cout<

}

else

{

cout<

}

}

cout<

for (int i=0;i

{

if(vec_b[i])

{

sta_i.push(vec[i]);

}

else

{

int t1=0;

int t2=0;

int t3=0;

if(!sta_i.empty())

{

t1=sta_i.top();

sta_i.pop();

}

if (!sta_i.empty())

{

t2=sta_i.top();

sta_i.pop();

}

if(vec[i]==43)

t3=t1+t2;

else if(vec[i]==45)

t3=t2-t1;

else if(vec[i]==42)

t3=t2*t1;

else if(vec[i]==47)

t3=t2/t1;

sta_i.push(t3);

}

}

if (!sta_i.empty())

res=sta_i.top();

cout<

while(!sta_i.empty())

sta_i.pop();

vec.clear();

}

return 0;

}

发表于 2016-04-13 15:50:01

回复(0)

更多回答

18

很激动所以过来贴代码啦~

思路是很正常的思路

  1. 先把中括号和大括号换成小括号,方便后续处理

  2. 四则运算

中缀表达式转后缀表达式,中途计算算出后缀表达式结果

#include

#include

#include//栈头文件

using namespace std;

string change_bracket(string exp);//将大括号和中括号转成小括号,同时,将负数x转成0-x的形式

int mid_to_post(string exp);

int calculate(int a, int b, char sym);

int main()

{

string exp;

while (cin >> exp)

{

exp = change_bracket(exp);

int exp_post = mid_to_post(exp);

cout << exp_post << endl;

}

return 0;

}

//把大括号和中括号换成小括号,以便减少后期过多的判断

string change_bracket(string exp)

{

for (int i = 0; i < exp.size(); i++)

{

if (exp[i] == ‘{‘ || exp[i] == ‘[‘)

exp[i] = ‘(‘;

if (exp[i] == ‘}‘ || exp[i] == ‘]‘)

exp[i] = ‘)’;

}

//cout << exp;

return exp;

}

int mid_to_post(string exp)

{

int flag = 0;//正负号标志,0为无正负号,1为正号,2为负号

stack exp_post;//数字栈

stack symbol;//符号栈

for (int i = 0; i < exp.size(); i++)

{

char temp;

if (isdigit(exp[i]))//为数字时

{

int j = i,num=0;

while (i + 1 < exp.length() && isdigit(exp[i + 1])) i++;

string str_num = exp.substr(j, i - j+1);

for (int k = 0; k < str_num.size(); k++)

num = num * 10 + str_num[k] - ‘0’;

if (flag == 2)

num = 0 - num;

flag = 0;

exp_post.push(num);

}

else if (exp[i] == ‘*‘ || exp[i] == ‘/‘ || exp[i] == ‘(‘)//为乘除时

symbol.push(exp[i]);

else if (exp[i] == ‘+’||exp[i] == ‘-‘)//为加减时

{

/*处理负号先*/

if (!i || exp[i - 1]==’(‘)

if (exp[i] == ‘+’)

flag = 1;

else

flag = 2;

/*处理负号先_end*/

while (!flag&&!symbol.empty() && symbol.top() != ‘(‘)//堆栈非空时,符号栈弹出符号,并结合数字栈计算

{

int b = 0, a = 0;

char sym_temp;

b = exp_post.top();

exp_post.pop();

a = exp_post.top();

exp_post.pop();

sym_temp = symbol.top();

symbol.pop();

exp_post.push(calculate(a, b, sym_temp));//计算结果入栈

}

if(!flag) symbol.push(exp[i]);

}

else if (exp[i] == ‘)’)//为右括号时

{

while (symbol.top() != ‘(‘)

{

int b = 0, a = 0;

char sym_temp;

b = exp_post.top();

exp_post.pop();

a = exp_post.top();

exp_post.pop();

sym_temp = symbol.top();

symbol.pop();

exp_post.push(calculate(a, b, sym_temp));//计算结果入栈

}

symbol.pop();

}

else

cout << “Input error!!!” << endl;

}

//循环结束后把剩下的符号弹出,并结合数字栈计算

while (!symbol.empty())

{

int b = 0, a = 0;

char sym_temp;

b = exp_post.top();

exp_post.pop();

a = exp_post.top();

exp_post.pop();

sym_temp = symbol.top();

symbol.pop();

exp_post.push(calculate(a, b, sym_temp));//计算结果入栈

}

return exp_post.top();

}

int calculate(int a,int b,char sym)

{

switch (sym)

{

case ‘+’: return a + b;

case ‘-‘: return a - b;

case ‘*‘: return a * b;

case ‘/‘: return a / b;

default:

return 0;

break;

}

}

编辑于 2017-06-21 22:19:08

回复(11)

24

传统方法,直接通过两个栈,计算中缀表达式的值 import java.util.*; public class Main{

// 用于存放一个正括号的集合, 用于简化代码

static Set brace = new HashSet<>();

public static void main(String … args){

Scanner sc = new Scanner(System.in);

// 初始化正括号集合

brace.add(‘{‘);

brace.add(‘(‘);

brace.add(‘[‘);

while(sc.hasNextLine()){

// 对字符串做初始化处理,原则有二:

// 1、处理负数,这里在-前面的位置加入一个0,如-4变为0-4,

// 细节:注意-开头的地方前面一定不能是数字或者反括号,如9-0,(3-4)-5,这里地方是不能加0的

// 它的后面可以是数字或者正括号,如-9=>0-9, -(3*3)=>0-(3*3)

// 2、处理字符串,在最后的位置加#, 主要是为了防止最后一个整数无法处理的问题

String exp = sc.nextLine().replaceAll(“(?

System.out.println(calculate(exp));

}

}

private static int calculate(String exp){

// 初始化栈

Stack opStack = new Stack<>();

Stack otStack = new Stack<>();

// 整数记录器

String num = “”;

for(int i = 0; i < exp.length(); i++){

// 抽取字符

char c = exp.charAt(i);

// 如果字符是数字,则加这个数字累加到num后面

if(Character.isDigit(c)){

num += c;

}

// 如果不是数字

else{

// 如果有字符串被记录,则操作数入栈,并清空

if(!num.isEmpty()){

int n = Integer.parseInt(num);

num = “”;

opStack.push(n);

}

// 如果遇上了终结符则退出

if(c == ‘#‘)

break;

// 如果遇上了+-

else if(c == ‘+’ || c == ‘-‘){

// 空栈或者操作符栈顶遇到正括号,则入栈

if(otStack.isEmpty() || brace.contains(otStack.peek())){

otStack.push(c);

} else {

// 否则一直做弹栈计算,直到空或者遇到正括号为止,最后入栈

while(!otStack.isEmpty() && !brace.contains(otStack.peek()))

popAndCal(opStack, otStack);

otStack.push(c);

}

}

// 如果遇上*/

else if(c == ‘*‘ || c == ‘/‘){

// 空栈或者遇到操作符栈顶是括号,或者遇到优先级低的运算符,则入栈

if(otStack.isEmpty()

|| brace.contains(otStack.peek())

|| otStack.peek() == ‘+’ || otStack.peek() == ‘-‘){

otStack.push(c);

}else{

// 否则遇到*或/则一直做弹栈计算,直到栈顶是优先级比自己低的符号,最后入栈

while(!otStack.isEmpty()

&& otStack.peek() != ‘+’ && otStack.peek() != ‘-‘

&& !brace.contains(otStack.peek()))

popAndCal(opStack, otStack);

otStack.push(c);

}

} else {

// 如果是正括号就压栈

if(brace.contains(c))

otStack.push(c);

else{

// 反括号就一直做弹栈计算,直到遇到正括号为止

char r = getBrace(c);

while(otStack.peek() != r){

popAndCal(opStack, otStack);

}

// 最后弹出正括号

otStack.pop();

}

}

}

}

// 将剩下的计算完,直到运算符栈为空

while(!otStack.isEmpty())

popAndCal(opStack, otStack);

// 返回结果

return opStack.pop();

}

private static void popAndCal(Stack opStack, Stack otStack){

int op2 = opStack.pop();

int op1 = opStack.pop();

char ot = otStack.pop();

int res = 0;

switch(ot){

case ‘+’:

res = op1 + op2;

break;

case ‘-‘:

res = op1 - op2;

break;

case ‘*‘:

res = op1 * op2;

break;

case ‘/‘:

res = op1 / op2;

break;

}

opStack.push(res);

}

private static char getBrace(char brace){

switch(brace){

case ‘)’:

return ‘(‘;

case ‘]‘:

return ‘[‘;

case ‘}‘:

return ‘{‘;

}

return ‘#‘;

}

}

发表于 2018-03-17 12:14:07

回复(0)

21

python solution: print(eval(input()))

编辑于 2017-09-07 19:39:30

回复(13)

15

//思路:

//1.字符串预处理,针对可能出现的“{,},[,],-”等特殊情况进行替换,判断‘-’是负号还是减号,负号前面+0,转变成减法运算

//2.将中缀字符串转变为后缀字符串数组

//3.对后缀字符串数组进行求解

#include

#include

#include

#include

#include

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

{

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 mid2post(string &str)

{

vectorvstr;

stackcstack;

for(int i=0;i

{

string temp=””;

if(str[i]>=’0’ && str[i]<=’9’)//若是数字

{

temp+=str[i];

while(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 & vstr)//对后缀表达式进行求值,主要是根据运算符取出两个操作数进行运算

{

int num,op1,op2;

stackopstack;

for(int i=0;i

{

string temp=vstr[i];

if(temp[0]>=’0’ && temp[0]<=’9’)//如果当前字符串是数字,利用字符串流转化为int型

{

stringstream ss;

ss<

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)

{

vectorvstr;

preProcess(str);//对字符串进行预处理

vstr=mid2post(str);//将中缀表达式转为后缀,保存在字符串数组中,方便下一步求解

int res=calcPostExp(vstr);

cout<

}

int main()

{

string str;

while(getline(cin,str))

{

calcExp(str);

}

return 0;

}

发表于 2017-03-18 17:34:32

回复(1)

5

#include

using namespace std;

int factor_value(); // 计算因子的值

int term_value(); // 计算多的值

int expression_value(); // 计算表达式的值

int expression_value()

{

int result = term_value();

bool more = true;

while(more) {

char op = cin.peek(); // 从输入流中查看当前指针指向的字符,指针并不后移。

if( op == ‘+’ || op == ‘-‘ ) {

cin.get(); // 从输入流中提取一个字符,指针往后移

int value = term_value();

if( op == ‘+’ ) result += value;

else result -= value;

}

else more = false;

}

return result;

}

int term_value()

{

int result = factor_value();

while(true) {

char op = cin.peek();

if(op == ‘*‘ || op==’/‘){

cin.get();

int value = factor_value();

if(op == ‘*‘) result *= value;

else result /= value;

}

else

break;

}

return result;

}

int factor_value()

{

int result = 0;

char c = cin.peek();

if(c == ‘(‘ || c == ‘[‘ || c == ‘{‘){

cin.get(); // 指针往后移,相当于去掉(或[或{

result = expression_value();

cin.get(); // 指针往后移,相当于去掉)或]或}

}

else {

while(isdigit(c)){ // isdigit(c)可以判断字符是否为数字。注意:上面使用char c定义变量,此处才能够判断。如果int c来定义这个变量,则判断不出来。

result = 10 * result + c - ‘0’; // 此处+c是加ascii码ord(c)值,所以需要减去0对应的ascii码值。

cin.get();

c = cin.peek();

}

}

return result;

}

int main()

{

cout <

return 0;

}

资料来源:中国大学MOOC之《程序设计与算法(二)算法基础》。

四则运算表达式,可以分为表达式、项、因子三个部分,其中因子可能是一个整数或一个表达式。因此需要判断后递归。

编辑于 2019-11-17 23:03:02

回复(0)

14

python ac代码如下:

老老实实按后缀表达式解法来写的== def pri(a):

if a == ‘(‘:

return 1

elif a == ‘+’ or a == ‘-‘:

return 2

elif a == ‘*‘ or a == ‘/‘:

return 3

def cal(a,b,c):

if c == ‘-‘:

return int(a) - int(b)

elif c == ‘+’:

return int(a) + int(b)

elif c == ‘*‘:

return int(a) * int(b)

elif c == ‘/‘:

return int(a)//int(b)

while True:

try:

s = input().strip()

data = []

yunsuan = []

s = s.replace(‘[‘,’(‘)

s = s.replace(‘{‘,’(‘)

s = s.replace(‘}‘,’)’)

s = s.replace(‘]‘,’)’)

i = 0

while i < len(s):

if s[i].isdigit(): #处理数字

j = i

while j < len(s) and s[j].isdigit() :

j = j + 1

data.append(s[i:j])

i = j

elif s[i] in [‘+’,’-‘,’*‘,’/‘]:

if s[i] == ‘-‘: #处理负数的情况,在-前面加上0

if i==0 or not s[i-1].isdigit() and s[i-1]!=’)’:

s = list(s)

s.insert(i,’0’)

s = ‘’.join(s)

continue

if not yunsuan:

yunsuan.append(s[i])

else:

if pri(s[i]) > pri(yunsuan[-1]):

yunsuan.append(s[i])

else:

while yunsuan and pri(s[i]) <= pri(yunsuan[-1]):

sym = yunsuan.pop()

data.append(sym)

yunsuan.append(s[i])

i = i+ 1

else:

if s[i] == ‘(‘:

yunsuan.append(s[i])

else:

while yunsuan[-1] != ‘(‘:

data.append(yunsuan.pop())

yunsuan.pop()

i = i + 1

while yunsuan:

data.append(yunsuan.pop())

#print(data)

j = 0

while len(data) != 1:

try:

fl = int(data[j])

j += 1

except:

t1 = data.pop(j)

t2 = data.pop(j-1)

data[j-2] = str(cal(data[j-2],t2,t1))

j = j - 1

print(data[0])

except:

break

编辑于 2020-04-11 17:33:32

回复(0)

34

print(input())

python一行就可以啊

发表于 2016-08-03 09:59:40

回复(17)

4

评论区都忘记eval函数了么。。。

while True:

try:

s = input().replace(‘{‘, ‘(‘).replace(‘}‘, ‘)’).replace(‘[‘, ‘(‘).replace(‘]‘, ‘)’)

res = eval(s)

print(int(res) if res == int(res) else res)

except:

break

发表于 2020-08-26 14:43:41

回复(1)

4

import java.util.*;

public class Main{

public static ArrayList infixToPostfix(ArrayList inExp){

int length = inExp.size();

ArrayList postExp = new ArrayList();

Stack stack = new Stack();

for(int i=0;i

String temp = inExp.get(i);

switch(temp){

case “(“:

stack.push(temp);

break;

case “+”:

case “-“:

while(stack.size()!=0){

String tempPop = stack.pop();

if(tempPop.equals(“(“)){

stack.push(tempPop);

break;

}

postExp.add(tempPop);

}

stack.push(temp);

break;

case “*“:

case “/“:

while(stack.size()!=0){

String tempPop = stack.pop();

if(tempPop.equals(“(“)||tempPop.equals(“+”)||tempPop.equals(“-“)){

stack.push(tempPop);

break;

}else{

postExp.add(tempPop);

}

}

stack.push(temp);

break;

case “)”://)不入栈

while(stack.size()!=0){

String tempPop = stack.pop();

if(tempPop.equals(“(“)){

//stack.push(tempPop);

break;

}else{

postExp.add(tempPop);

}

}

break;

default:

postExp.add(temp);

break;

}

}

while(stack.size()!=0){

postExp.add(stack.pop());

}

return postExp;

}

public static int postfixToResult(ArrayList postfixExp){

Stack stack = new Stack();

int expLength = postfixExp.size();

ArrayList expTemp = new ArrayList();

//去掉空格的东西

for(int i=0;i

if(postfixExp.get(i).trim().length()!=0){

expTemp.add(postfixExp.get(i));

}

}

int length = expTemp.size();

for(int i=0;i

if(!expTemp.get(i).matches(“[\\(\\)\\+\\-\\*\\/]“)){

stack.push(Integer.parseInt(expTemp.get(i)));

}else{

int first = stack.pop();

int second = stack.pop();

stack.push(getResult(first,second,expTemp.get(i)));

}

}

return stack.pop();

}

public static int getResult(int first,int second,String symbol){

if(symbol.equals(“+”)){

return first+second;

}else if(symbol.equals(“-“)){

return second-first;

}else if(symbol.equals(“*“)){

return first*second;

}else if(symbol.equals(“/“)){

return second/first;

}

return 0;

}

public static ArrayList getExpression(String exp){

exp = exp.trim();

exp = exp.replaceAll(“[\\[\\{]“, “(“);

exp = exp.replaceAll(“[\\]\\}]“, “)”);

int expLength = exp.length();

StringBuilder inSb = new StringBuilder();

for(int i=0;i

String tempStr = String.valueOf(exp.charAt(i));

if(tempStr.matches(“[\\(\\)\\+\\-\\*\\/]“)){

inSb.append(“,”);

inSb.append(tempStr);

inSb.append(“,”);

}else{

inSb.append(tempStr);

}

}

String[] inArr = inSb.toString().split(“\\,+”);

ArrayList inStr = new ArrayList(Arrays.asList(inArr));

ArrayList numList = new ArrayList();

if(inStr.get(0).equals(“-“)){

inStr.set(1, “-“+inStr.get(1));

numList.add(0);

}else{

for (int i=1;i

if(inStr.get(i).equals(“-“)){

if(inStr.get(i-1).matches(“[\\+\\/\\-\\*\\(]“)){//前一个是数字)后面可以有

inStr.set(i+1,”-“+inStr.get(i+1));

numList.add(i);

}

}

}

}

ArrayList endList = new ArrayList();

for(int i=0;i

if(!numList.contains(i)){

endList.add(inStr.get(i));

}

}

return endList;

}

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

while(scanner.hasNextLine()){

String arthLine = scanner.nextLine();

if(arthLine.trim().length()!=0){

System.out.println(postfixToResult(infixToPostfix(getExpression(arthLine))));

}

}

}

}

发表于 2017-12-27 21:28:13

回复(0)

4

#include

#include

#include

#include

using namespace std;

inline bool isAOpt(char ch) {

if (ch == ‘+’ || ch == ‘-‘ || ch == ‘*‘ || ch == ‘/‘)

return true;

return false;

}

vector nifix2postfix(string str) {

vector strvec;

stack optstk;

int i = 0, sz = str.size();

while (i < sz) {

if (str[i] >= ‘0’ && str[i] <= ‘9’) { //如果是一个数字

auto pos = str.find_first_of(“+-*/{}[]()”, i);

if (pos == string::npos) pos = sz;

strvec.push_back(str.substr(i, pos - i));

i = pos;

}

else if (str[i] == ‘+’ || str[i] == ‘-‘) { //str[i]是 + 或 - 时

if (i == 0 || str[i - 1]==’(‘ || str[i - 1] == ‘[‘ || str[i - 1] == ‘{‘) //表示不是一个加减号,而是一个数字的正负号,在前面补一个0

strvec.push_back(“0”);

while (!optstk.empty() && (optstk.top() == ‘+’ || optstk.top() == ‘-‘ || optstk.top() == ‘*‘ || optstk.top() == ‘/‘)) {

strvec.push_back(string(1, optstk.top()));

optstk.pop();

}

optstk.push(str[i++]);

}else if (str[i] == ‘*‘ || str[i] == ‘/‘) {

while (!optstk.empty() && (optstk.top() == ‘*‘ || optstk.top() == ‘/‘)) {

strvec.push_back(string(1, optstk.top()));

optstk.pop();

}

optstk.push(str[i++]);

}

else if (str[i] == ‘(‘ || str[i] == ‘[‘ || str[i] == ‘{‘) {

optstk.push(str[i++]);

}

else if (str[i] == ‘)’ || str[i] == ‘]‘ || str[i] == ‘}‘) {

while (optstk.top() != ‘(‘ && optstk.top() != ‘[‘ && optstk.top() != ‘{‘) {

strvec.push_back(string(1, optstk.top()));

optstk.pop();

}

optstk.pop();

i++;

}

}

while (!optstk.empty()) {

strvec.push_back(string(1, optstk.top()));

optstk.pop();

}

return strvec;

}

int calcPostfix(vector strvec) {

stack stk;

int ret = 0;

for (int i = 0; i < strvec.size(); ++i) {

if (strvec[i] != “+” && strvec[i] != “-“ && strvec[i] != “*“ && strvec[i] != “/“)

stk.push(stoi(strvec[i]));

else {

if (stk.size() == 1) break;

int n1 = stk.top(); stk.pop();

int n2 = stk.top(); stk.pop();

if (strvec[i] == “+”) n2 += n1;

if (strvec[i] == “-“) n2 -= n1;

if (strvec[i] == “*“) n2 *= n1;

if (strvec[i] == “/“) n2 /= n1;

stk.push(n2);

}

}

return stk.top();

}

int main() {

string str;

getline(cin, str);

cout << calcPostfix(nifix2postfix(str));

return 0;

}

发表于 2017-06-12 23:23:12

回复(1)

10

//先中缀转后缀再计算后缀表达式的值,需要注意的是对于‘-’为一元运算符的处理和数字//的位数做一个记录。当看到python只有一行代码时,吐了一口老血。。。

#include

#include

#include

#include

using namespace std;

int main() {

string s;

while (cin >> s) {

stack opera;

vector numcnt;//用来保存每个数字的位数,以保证计算后缀表达式时的正确性

string s1;//后缀表达式

//中缀表达式转后缀表达式

for (int i = 0;i

if (s[i] >= ‘0’&&s[i] <= ‘9’) {

int tmp = 0;

while (s[i] >= ‘0’&&s[i] <= ‘9’) {

tmp++;

s1 += s[i];

i++;

}

i—;

numcnt.push_back(tmp);

}

else if (s[i] == ‘-‘ || s[i] == ‘+’) {

if (s[i] == ‘-‘ && (s[i - 1] == ‘(‘ || s[i - 1] == ‘[‘ || s[i - 1] == ‘{‘))

s1 += ‘0’;

while (!opera.empty()&&(opera.top() == ‘*‘ || opera.top() == ‘/‘ || opera.top() == ‘+’ || opera.top() == ‘-‘)) {

s1 += opera.top();

opera.pop();

}

opera.push(s[i]);

}

else if (s[i] == ‘*‘ || s[i] == ‘/‘) {

while (!opera.empty()&&(opera.top() == ‘*‘ || opera.top() == ‘/‘)) {

s1 += opera.top();

opera.pop();

}

opera.push(s[i]);

}

else if (s[i] == ‘(‘ || s[i] == ‘[‘ || s[i] == ‘{‘)

opera.push(s[i]);

else if (s[i] == ‘)’) {

while (opera.top() != ‘(‘) {

s1 += opera.top();

opera.pop();

}

opera.pop();

}

else if (s[i] == ‘]‘) {

while (opera.top() != ‘[‘) {

s1 += opera.top();

opera.pop();

}

opera.pop();

}

else if (s[i] == ‘}‘) {

while (opera.top() != ‘{‘) {

s1 += opera.top();

opera.pop();

}

opera.pop();

}

else

cout << “Invalid input!” << endl;

}

while (!opera.empty()) {

s1 += opera.top();

opera.pop();

}

//计算后缀表达式的值

stack nums;

int ind = 0;

for (int i = 0;i

if (s1[i] >= ‘0’&&s1[i] <= ‘9’) {

int total = 0;

while (numcnt[ind]—)

total = 10 * total + (s1[i++] - ‘0’);

i—;

nums.push(total);

ind++;

}

else {

int tmp1 = nums.top();

nums.pop();

int tmp2 = nums.top();

nums.pop();

if (s1[i] == ‘+’)

nums.push(tmp2 + tmp1);

else if (s1[i] == ‘-‘)

nums.push(tmp2 - tmp1);

else if (s1[i] == ‘*‘)

nums.push(tmp2*tmp1);

else

nums.push(tmp2 / tmp1);

}

}

cout << nums.top() << endl;

}

}

编辑于 2017-06-12 17:35:16

回复(8)

3

#include

#include

#include

#include

#include

using namespace std;

int ispriority(char a)//确定优先级

{

int flag;

if (a == ‘+’ || a == ‘-‘)

flag = 1;

if (a == ‘*‘ || a == ‘/‘)

flag = 2;

return flag;

}

int main()

{

string str;

while (cin >> str)

{

for (int i = 0; i < str.size(); i++)//将大括号和中括号变为小括号,方便使用

{

if (str[i] == ‘[‘ || str[i] == ‘{‘)

str[i] = ‘(‘;

if (str[i] == ‘]‘ || str[i] == ‘}‘)

str[i] = ‘)’;

if (str[i] == ‘-‘ && (i == 0 || str[i - 1] == ‘(‘))//区分负号和减号,负数在负号前面加0

str.insert(i, “0”);

}

vector v;

stack s;

for (int i = 0; i < str.size(); i++)

{

string str1;

if (str[i] >= ‘0’&&str[i] <= ‘9’)//数字输出

{

str1 += str[i];

while (i + 1 < str.size() && str[i + 1] >= ‘0’&&str[i + 1] <= ‘9’)//大于等于10的数的输出

{

str1 += str[i + 1];

i++;

}

v.push_back(str1);

}

else

{

if (s.empty())//栈为空则进栈

s.push(str[i]);

else

{

if (str[i] == ‘(‘)//左括号进栈

{

s.push(str[i]);

}

else if (str[i] == ‘)’)//右括号则括号内的元素出栈,直到左括号为止

{

while (s.top() != ‘(‘)

{

string str2;

str2 += s.top();

v.push_back(str2);

s.pop();

}

s.pop();//左括号也出栈

}

else if (str[i] == ‘+’ || str[i] == ‘-‘ || str[i] == ‘*‘ || str[i] == ‘/‘)

{

while (s.size() != 0 && s.top() != ‘(‘ && ispriority(str[i]) <= ispriority(s.top()))

{

string str3;//优先级不高于栈顶则栈内元素出栈直到遇见高优先级运算符号

str3 += s.top();

v.push_back(str3);

s.pop();

}

s.push(str[i]);//高优先级运算符出栈完成,低优先级运算符进栈

}

}

}

}

while (!s.empty())//将栈中运算符依次出栈

{

string str4;

str4 += s.top();

v.push_back(str4);

s.pop();

}

/*for (int i = 0; i < v.size(); i++)

{

cout << v[i]<

}

cout << endl;*/

stack s1;//数字栈

for (int i = 0; i < v.size(); i++)

{

if (v[i][0] >= ‘0’&&v[i][0] <= ‘9’)

s1.push(stoi(v[i]));//数字串转为整型数字,并将数字进数字栈

else//遇见运算符,数字栈抛出两个元素,与运算符进行运算,结果进栈。

{ //其中第一个出栈元素位于运算符右侧,第二个出栈元素在运算符左侧。

int m, n;

m = s1.top();

s1.pop();

n = s1.top();

s1.pop();

if (v[i] == “+”)

s1.push(m + n);

if (v[i] == “-“)

s1.push(n - m);

if (v[i] == “*“)

s1.push(m*n);

if (v[i] == “/“)

s1.push(n / m);

}

}

cout << s1.top() << endl;//最后数字栈只剩一个元素,就是运算结果。

}

return 0;

}

编辑于 2019-05-03 11:21:14

回复(1)

3

//利用了递归求解,程序十分简短

#include

#include

#include

#include

using namespace std;

void addNum(deque& Q,int num){

if(!Q.empty()){

int cur=0;

if(Q.back()==”*“||Q.back()==”/“){

string top=Q.back();

Q.pop_back();

stringstream ss(Q.back());

ss>>cur;

Q.pop_back();

num=top==”*“?(cur*num):(cur/num);

}

}

stringstream ss;

ss<

Q.push_back(ss.str());

}

int getNum(deque& Q){

int num=0,R=0;

string f(“+”);

while(!Q.empty()){

stringstream ss(Q.front());

ss>>num;

Q.pop_front();

R=(f==”+”)?(R+num):(R-num);

if(!Q.empty()){

f=Q.front();

Q.pop_front();

}

}

return R;

}

int* value(string& s,int i){

deque Q;

int pre=0;

while(i

if(s[i]>=’0’&&s[i]<=’9’){

pre=pre*10+s[i++]-‘0’;

}else if(s[i]!=’(‘&&s[i]!=’[‘&&s[i]!=’{‘){

addNum(Q,pre);

string ss;

ss+=s[i++];

Q.push_back(ss);

pre=0;

}else{

int* bra=NULL;

bra=value(s,i+1);

pre=bra[0];

i=bra[1]+1;

}

}

addNum(Q,pre);

int *R=new int[2];

R[0]=getNum(Q);

R[1]=i;

return R;

}

int main(){

string s;

while(cin>>s){

int *R=value(s,0);

cout<

}

return 0;

}

编辑于 2016-08-11 17:47:07

回复(1)

5

#include

#include

#include

#include

#include

using namespace std;

stack sig;

stack nums;

map dict= { {‘]‘,’[‘},{‘)’,’(‘},{‘}‘,’{‘}};

int core(int num1,int num2,char c)

{

if(c==’+’)

return num1+num2;

if(c==’-‘)

return num2-num1;

if(c==’*‘)

return num1*num2;

return num1/num2;

}

void calc()

{

int num1=nums.top();

nums.pop();

int num2=nums.top();

nums.pop();

nums.push(core(num1,num2,sig.top()));

sig.pop();

}

int main()

{

string s;

while(cin>>s)

{

int l=s.length();

stringstream ss;

int tp;

for(int i=0;i

{

if(s[i]>=’0’&&s[i]<=’9’)

{

int j=i;

while(j=’0’&&s[j]<=’9’)

j++;

ss<

ss>>tp;

nums.push(tp);

ss.clear();

i=—j;

continue;

}

else if(s[i]==’+’||s[i]==’-‘)

{

while(!sig.empty()&&(sig.top()==’/‘||sig.top()==’*‘||sig.top()==’+’||sig.top()==’-‘))

calc();

}

else if(s[i]==’/‘||s[i]==’*‘)

{

while(!sig.empty()&&(sig.top()==’/‘||sig.top()==’*‘))

calc();

}

else if(dict.count(s[i]))

{

char c=dict[s[i]];

while(!sig.empty()&&sig.top()!=c)

calc();

sig.pop();

continue;

}

sig.push(s[i]);

}

while(!sig.empty())

calc();

cout<

nums.pop();

}

}

发表于 2018-07-07 10:28:48

回复(3)

7

Python大法好呀

发表于 2017-06-04 19:47:56

回复(0)

2

import java.util.ArrayList;

import java.util.Scanner;

import java.util.Stack;

public class Main {

private static Stack stack = new Stack<>();

private static StringBuilder postFix = new StringBuilder();

private static ArrayList digitCnt = new ArrayList<>();

public static void main(String[] args) {

Scanner sc= new Scanner(System.in);

while (sc.hasNext()) {

String str = sc.next();

String postFix = trans(str);

int res = cal(postFix);

System.out.println(res);

}

}

//中缀表达式转成后缀表达式

static String trans(String inFix){

String newInFix = inFix.replace(‘{‘, ‘(‘) //都换成小括号

.replace(‘}‘, ‘)’)

.replace(‘]‘, ‘)’)

.replace(‘[‘, ‘(‘);

char[] chars = newInFix.toCharArray();

for (int i = 0; i < chars.length; ++i){

if (Character.isDigit(chars[i])){

int temp = 0;

//加上i < chars.length,否则数组越界

while (i < chars.length && Character.isDigit(chars[i])) {

postFix.append(chars[i]);

++i;

++temp;

}

--i;

digitCnt.add(temp);

}else if (chars[i] == ‘(‘){

stack.push(chars[i]);

}else if (chars[i] == ‘+’ || chars[i] == ‘-‘){

if (chars[i] == ‘-‘ && chars[i - 1] == ‘(‘){

postFix.append(‘0’);

digitCnt.add(1);

}

while (!stack.isEmpty() && (stack.peek() == ‘*‘ || stack.peek() == ‘/‘ || stack.peek() == ‘+’ || stack.peek() == ‘-‘)){

postFix.append(stack.peek());

stack.pop();

}

stack.push(chars[i]);

}else if (chars[i] == ‘*‘ || chars[i] == ‘/‘){

while (!stack.isEmpty() && (stack.peek() == ‘*‘ || stack.peek() == ‘/‘)){

postFix.append(stack.peek());

stack.pop();

}

stack.push(chars[i]);

}else {

while (!stack.isEmpty() && stack.peek() != ‘(‘){

postFix.append(stack.peek());

stack.pop();

}

stack.pop();

}

}

while (!stack.isEmpty()){

postFix.append( stack.pop());

}

return postFix.toString();

}

//计算后缀表达式的值

static int cal(String postFix){

int index = 0;

Stack stack1 = new Stack<>();

char[] chas = postFix.toCharArray();

for (int i = 0; i < chas.length; i++) {

if (Character.isDigit(chas[i])){

int total = 0;

int cnt = digitCnt.get(index);

while (cnt— > 0){

total = 10 * total + (chas[i++] - ‘0’);

}

--i;

stack1.push(total);

++index;

}else {

int num1 = stack1.peek();

stack1.pop();

int num2 = stack1.peek();

stack1.pop();

if (chas[i] == ‘+’){

stack1.push(num1 + num2);

}else if (chas[i] == ‘-‘){

stack1.push(num2 - num1);

}else if (chas[i] == ‘*‘){

stack1.push(num1 * num2);

}else {

stack1.push(num2 / num1);

}

}

}

return stack1.peek();

}

}

编辑于 2019-06-18 20:28:24

回复(0)

2

javascript 不用 eval() 解法,正则表达式绕了我好久,欢迎改进。

while(line=readline()){ var str = line.trim();

var str = str.replace(/[\{\[]/g,”(“).replace(/[\}\]]/g,”)”);

console.log(cal(str));

}

function cal(str){

var reg = /\(([^\(\)]+)\)/g;

while(reg.test(str)){

str = str.replace(reg,function($1,$2){

return cal2($2);

})

}

return cal2(str);

} function cal2(str){

var arr = [];

var sub = “”;

for(var i = 0; i < str.length; i++){

if(/[\+\*\/-]/.test(str[i]) && !(/[\+\*\/-]/.test(str[i-1]))){

arr.push(sub);

sub = “”;

arr.push(str[i]);

}else{

sub += str[i];

}

}

arr.push(sub);

var temp = [];

var result = [];

for(var i = 0; i < arr.length; i++){

if(/[\*\/]/.test(arr[i])){

var num1 = Number(temp.pop());

var num2 = Number(arr[i+1]);

if(arr[i] == “*“){

temp.push(num1*num2);

}else{

temp.push(num1/num2);

}

i++;

}else{

temp.push(arr[i]);

}

}

for(var i = 0; i < temp.length; i++){

if(/[\+-]/.test(temp[i])){

var num1 = Number(result.pop());

var num2 = Number(temp[i+1]);

if(temp[i] == “+”){

result.push(num1+num2);

}else{

result.push(num1-num2);

}

i++;

}else{

result.push(temp[i]);

}

}

return result[0];

}

发表于 2018-08-06 20:50:22

回复(1)

2

#include

#include

#include

#include

using namespace std;

//先转为逆波兰表达式再求值

class Solution {

public:

int evaluateExpression(vector &expression) {

if (expression.empty()) return 0;

vector op;//符号栈

vector exp;//结果栈

for (unsigned int i = 0; i < expression.size(); ++i)

{//逐个扫描

if (expression[i] == “+” || expression[i] == “-“)

{//处理”+”,”-“

if (op.size() == 0)

op.push_back(expression[i]);

else {//满足以下情况一直出栈

while (op.size() != 0 && (op[op.size() - 1] == “+” || op[op.size() - 1] == “-“ || op[op.size() - 1] == “*“ || op[op.size() - 1] == “/“))

{

string s = op.back();

op.pop_back();

int op2 = exp.back();

exp.pop_back();

int op1 = exp.back();

exp.pop_back();

if (s == “+”) exp.push_back(op1 + op2);

else if (s == “-“) exp.push_back(op1 - op2);

else if (s == “*“) exp.push_back(op1 * op2);

else exp.push_back(op1 / op2);

}

op.push_back(expression[i]);

}

}//end +,-

else if (expression[i] == “*“ || expression[i] == “/“)

{//处理*,/

if (op.size() == 0)

op.push_back(expression[i]);

else if (op[op.size() - 1] == “*“ || op[op.size() - 1] == “/“)

{

string s = op.back();

op.pop_back();

int op2 = exp.back();

exp.pop_back();

int op1 = exp.back();

exp.pop_back();

if (s == “*“) exp.push_back(op1 * op2);

else exp.push_back(op1 / op2);

op.push_back(expression[i]);

}

else

op.push_back(expression[i]);

}//end *,/

else if (expression[i] == “(“) {

op.push_back(expression[i]);

}

else if (expression[i] == “)”)

{//处理右括号

while (op.back() != “(“)

{

string s = op.back();

op.pop_back();

int op2 = exp.back();

exp.pop_back();

int op1 = exp.back();

exp.pop_back();

if (s == “+”) exp.push_back(op1 + op2);

else if (s == “-“) exp.push_back(op1 - op2);

else if (s == “*“) exp.push_back(op1 * op2);

else exp.push_back(op1 / op2);

}

op.pop_back();

}//end )

else

{//处理数字

exp.push_back(atoi(expression[i].c_str()));

}//done

}//end if

while (!op.empty())

{

string s = op.back();

op.pop_back();

int op2 = exp.back();

exp.pop_back();

int op1 = exp.back();

exp.pop_back();

if (s == “+”) exp.push_back(op1 + op2);

else if (s == “-“) exp.push_back(op1 - op2);

else if (s == “*“) exp.push_back(op1 * op2);

else exp.push_back(op1 / op2);

}

if (exp.empty()) return 0;

return exp[0];

}

};

void preDeal(vector& res, string str) {

for (int i = 0; i < str.size();++i) {

if (str[i] == ‘+’ || str[i] == ‘*‘ ||

str[i] == ‘/‘ || str[i] == ‘(‘ || str[i] == ‘)’)

res.push_back(str.substr(i, 1));

else if (str[i] == ‘-‘) {

if (i == 0 || (!isalnum(str[i - 1]) && str[i - 1] != ‘)’)) res.push_back(“0”);

res.push_back(“-“);

}

else if (str[i] == ‘{‘ || str[i] == ‘[‘)

res.push_back(“(“);

else if (str[i] == ‘}‘ || str[i] == ‘]‘)

res.push_back(“)”);

else {//digit(s?)

int j = 1;

while (i + j < str.size() && isalnum(str[i + j])) ++j;

res.push_back(str.substr(i, j));

i += j - 1;

}

}

}

int main() {

string str;

Solution s;

while (getline(cin, str)) {

vector tmp;

preDeal(tmp, str);

//for (auto s : tmp) cout << s << “ “;

cout << s.evaluateExpression(tmp) << endl;

}

return 0;

}

发表于 2017-03-17 15:00:00

回复(0)

3

两行搞定

发表于 2016-03-16 18:26:13

回复(6)

2

print(int(eval(input().replace(“{“,”(“).replace(“}“,”)”).replace(“[“,”(“).replace(“]“,”)”))))

发表于 2020-02-20 22:38:43

回复(0)

发表评论

表情:
评论列表 (有 0 条评论,138人围观)

还没有评论,来说两句吧...

相关阅读

    相关 有理数四则运算

    本题要求编写程序,计算 2 个有理数的和、差、积、商。 输入格式: 输入在一行中按照 a1/b1 a2/b2 的格式给出两个分数形式的有理数,其中分子和分母全是整型范围