当前位置:   article > 正文

#力扣 LeetCode224. 基本计算器 @FDDLC_力扣带括号的计算

力扣带括号的计算

题目描述:

https://leetcode-cn.com/problems/basic-calculator/

 

Java代码:

  1. class Solution { //数字、+-、()、空格
  2. public int calculate(String s) {
  3. char[] a=new char[s.length()+1];//a[a.length-1]为'\0',充当边界屏障
  4. int ans=0,top=0,slen=s.length(),num=0,operand=1,ai=0;//top为栈指针,operand为当前操作数的直接符号(操作数的正负还结结合父括号的正负来判断))
  5. for(int si=0;si<slen;si++)if(s.charAt(si)!=' ')a[ai++]=s.charAt(si);
  6. int[] operandStack=new int[ai];//1表示正,-1表示负
  7. operandStack[0]=1;//[0]为默认值1,表示栈底(避免对栈底进行单独处理))
  8. for(int i=0;i<ai;i++){
  9. if(a[i]>='0'){//本题a[i]>='0'即可判断是数字字符
  10. num=a[i]-'0'+num*10;//要防溢出
  11. if(a[i+1]<'0'){ //i+1要防越界
  12. ans+=num*operand*operandStack[top];
  13. num=0;
  14. operand=1;
  15. }
  16. }else if(a[i]=='('){
  17. operandStack[top+1]=operandStack[top++]*operand;//之后top++
  18. operand=1;
  19. }else if(a[i]==')')top--;
  20. else if(a[i]=='-')operand=-operand;
  21. }
  22. return ans;
  23. }
  24. }

 

 

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/848169
推荐阅读
相关标签
  

闽ICP备14008679号