题解 | #牛牛计算器#
牛牛计算器
https://www.nowcoder.com/practice/192ac31d5e054abcaa10b72d9b01cace
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
public int calculate (String s) {
// write code here
Stack<Integer> nums = new Stack<>();
int num = 0;
char operation = '+';
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = num * 10 + c - '0';
} else if (c == '(') {
int j = i, cnt = 0;
for (; i < s.length(); ++i) {
if (s.charAt(i) == '(') ++cnt;
if (s.charAt(i) == ')') --cnt;
if (cnt == 0)
break;
}
num = calculate(s.substring(j + 1,
i));
}
if (!Character.isWhitespace(c) || i == s.length() - 1) {
if (operation == '+') {
nums.push(num);
} else if (operation == '-') {
nums.push(-num);
} else if (operation == '*') {
int temp = nums.pop() * num;
nums.push(temp);
}
num = 0;
operation = c;
}
}
int result = 0;
while (!nums.isEmpty()) {
result += nums.pop();
}
return result;
}
}
本题知识点分析:
1.栈的入栈和出栈
2.API函数判断是否为空格,数字,字符,可以掌握一下
3.字符串取字符
4.数学模拟
本题解题思路分析:
1.先判断是否为数字,如果是,将数字由Ascii先进行转化
2.注意特殊情况,如果有括号,那么左括号和右括号形成闭合区间,此区间内优先级高
3.注意减号和除号,是要区分前后顺序的,其他可以不区分顺序

深信服公司福利 795人发布