一、描述
请写一个整数计算器,支持加减乘三种运算和括号。
二、思路
三、实现
public int calculate(String s) {
s = s.trim();
Deque<Integer> stack = new ArrayDeque<>();
int number = 0;
char sign = '+';
char[] charArray = s.toCharArray();
for (int i = 0, n = charArray.length; i < n; i++) {
char c = charArray[i];
if (c == ' ') {
continue;
}
if (Character.isDigit(c)) {
number = number * 10 + c - '0';
}
if (c == '(') {
int j = i + 1;
int counterPartition = 1;
while (counterPartition > 0) {
if (charArray[j] == '(') {
counterPartition++;
}
if (charArray[j] == ')') {
counterPartition--;
}
j++;
}
number = calculate(s.substring(i + 1, j - 1));
i = j - 1;
}
if (!Character.isDigit(c) || i == n - 1) {
if (sign == '+') {
stack.push(number);
} else if (sign == '-') {
stack.push(-1 * number);
} else if (sign == '*') {
stack.push(stack.pop() * number);
} else if (sign == '/') {
stack.push(stack.pop() / number);
}
number = 0;
sign = c;
}
}
int ans = 0;
while (!stack.isEmpty()) {
ans += stack.pop();
}
return ans;
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 返回表达式的值
* @param s string字符串 待计算的表达式
* @return int整型
*/
function solve( s ) {
let results = s.matchAll(/[+\-*()]|[0-9]+/g);
results =Array.from(results).map(item=>{
if(Number(item[0])){
return Number(item[0]);
}else{
return item[0];
}
});
let stack = [],postfix = [];
for(let i =0;i<results.length;i++){
if(typeof results[i] == 'number'){
postfix.push(results[i]);
}else if(results[i] == '('){
stack.push(results[i]);
}else if(results[i] =='+'||results[i]=='-'){
while(stack.length != 0 && stack[stack.length-1] != '('){
postfix.push(stack.pop());
}
stack.push(results[i]);
}else if(results[i] == ')'){
while(stack[stack.length-1] !='('){
postfix.push(stack.pop());
}
stack.pop();
}else if(results[i] == '*'){
while(stack.length!=0 && stack[stack.length-1]!="("
&& stack[stack.length-1]!="+" && stack[stack.length-1]!="-"){
postfix.push(stack.pop());
}
stack.push(results[i]);
}
}
while(stack.length != 0){
postfix.push(stack.pop());
}
for(let i =0;i<postfix.length;i++){
if(typeof postfix[i] == 'number'){
stack.push(postfix[i]);
}else{
let a = stack.pop();
let b = stack.pop();
switch(postfix[i]){
case '+':
stack.push(a+b);
break;
case '-':
stack.push(b-a);
break;
case '*':
stack.push(a*b);
break;
}
}
}
return stack.pop();
}
module.exports = {
solve : solve
};