題目
/***
* 基本計(jì)算器
* https://leetcode-cn.com/problems/basic-calculator/
* 實(shí)現(xiàn)一個(gè)基本的計(jì)算器來(lái)計(jì)算一個(gè)簡(jiǎn)單的字符串表達(dá)式的值遗菠。
* 思路:
* 從左往右遍歷
* 如果是數(shù)字(考慮多多位數(shù))
* 例如 678 --> 0 * 10 + 6 = 6 ---> 6 * 10 + 7 = 67 ---> 67 * 10 + 8 = 678
* 即 operand = operand * 10 + (int) (charStr - '0');
* 如果遇到 ' ( ' 就 把之前計(jì)算結(jié)果和正負(fù)號(hào) push 進(jìn)棧 , 遇到 ')' 取出之前結(jié)果, 出棧累加
*
*/
Java實(shí)現(xiàn)
public static int calculate(String s) {
Stack<Integer> stack = new Stack<>();
int operand = 0; // 記錄多位數(shù)
int result = 0; // 結(jié)果
int sign = 1; // 記錄正負(fù)號(hào)
for (int i = 0; i < s.length(); i++) {
char charStr = s.charAt(i);
if (Character.isDigit(charStr)) { // 如果是數(shù)字
operand = operand * 10 + (int) (charStr - '0');
} else if (charStr == '+') {
result += sign * operand;
sign = 1;
operand = 0;
} else if (charStr == '-') {
result += sign * operand;
sign = -1;
operand = 0;
} else if (charStr == '(') {
// 把之前的結(jié)果和正負(fù)符號(hào) 存入棧
stack.push(result);
stack.push(sign);
result = 0;
sign = 1;
} else if (charStr == ')') {
// 計(jì)算括號(hào)內(nèi)的結(jié)果
result += sign * operand;
// 取出小括號(hào)之前的符號(hào)
int tempSign = stack.pop();
// 取出之前的結(jié)果 * 正負(fù)號(hào)
result = stack.pop() + result * tempSign;
//復(fù)位
operand = 0;
}
}
return result + sign * operand;
}