题目描述
解析加减法运算
如:
输入字符串:“1+2+3” 输出:“6”
输入字符串:“1+2-3” 输出:“0”
输入字符串:"-1+2+3" 输出:“4”
输入字符串:“1” 输出:“1”
输入字符串:"-1" 输出:"-1"
已知条件:输入的运算都是整数运算,且只有加减运算
要求:输出为String类型,不能使用内建的eval()函数
输入描述:
输入字符串:"1+2+3"
输出描述:
输出:"6"
示例1
输入
1+2+3
输出
6
思路:用两个栈分别保存每个数和每个操作符,以此将栈顶元素取出对应起来,计算结果
代码:
import java.util.Scanner;
import java.util.Stack;
public class Main{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
Stack<Integer> num = new Stack<>();
Stack<Character> c = new Stack<>();
String str = s.next();
String n = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i)=='+'||str.charAt(i)=='-'){
if(n!=""){
num.add(Integer.parseInt(n));
n="";
}
c.add(str.charAt(i));
}else{
n += str.charAt(i);
}
}
num.add(Integer.parseInt(n));
int ans = 0;
while (!num.isEmpty()){
int a = num.pop();
char b ='+';
if(!c.isEmpty()){
b = c.pop();
}
if(b=='-'){
ans -= a;
}else{
ans += a;
}
}
System.out.println(ans);
}
}