public int calculate(String s) {
LinkedList<Integer> stack = new LinkedList<>();
int res = 0 ;
int flag = 1;
for (int i = 0; i < s.length() ; i++) {
char c = s.charAt(i);
if(Character.isDigit(c))
{
int temp = c - '0';
while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1)))
{
temp *= 10 ;
temp += s.charAt( ++i) - '0';
}
res += flag * temp;
}
if(s.charAt(i) == '+')
flag = 1;
if(s.charAt(i) == '-')
flag = -1;
if(s.charAt(i) == '(')
{
stack.push(res);
res = 0;
stack.push(flag);
flag = 1;
}
if(s.charAt(i) ==')')
{
res = res * stack.pop() + stack.pop();
}
}
return res;
}
基本计算器
最新推荐文章于 2024-08-29 11:01:35 发布