Basic Calculator

来源:互联网 发布:php新闻上传系统 编辑:程序博客网 时间:2024/05/16 01:49

问题描述:

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2" 2-1 + 2 " = 3"(1+(4+5+2)-3)+(6+8)" = 23
思路:以前数据结构的课程上大概提到过,所以第一感觉就是两个栈来完成这个题目,但是在写之前还是先搜索了一下。结果发现一个比价优秀的实现,链接在此:点击打开链接

人家是java实现的,理解人家的思路之后自己用c++敲了一次。代码如下:

class Solution {public:    int calculate(string s) {        if(s.size() == 0) return 0;//如果是个特殊的空字符串直接输出0,程序结束        int sign = 1;//本代码亮点所在,将+-符号直接转化成了因子1和-1;        int result = 0;        stack<int> resultStack;        for(int i = 0; i< s.size(); i++){            if(isdigit(s[i])){                                 int currentDigit = s[i] - '0'; //如果当前的字符是数字,先把当前的这个字符转换成0-9数字                while(i < s.size() && isdigit(s[i + 1])) //然而这还没有完,如果下一个还是字符,应该如下处理                    currentDigit = currentDigit * 10 + s[++i] - '0';//这里注意了是将i加1,然后在将这个位置的字符转化成数字                result = result + currentDigit * sign;            }else if(s[i] == '+'){                sign = 1;            }else if(s[i] == '-'){                sign = -1;            }else if(s[i] == '('){                resultStack.push(result);//如果是(那么将之前的结果暂存在栈中,因为本题假设输入的字符串都是合法的,即在                               (出现之前肯定有一个+或者-,所以将之前的这个用sign暂存在栈中                resultStack.push(sign);                result = 0;                sign = 1;            }else if(s[i] == ')'){                int priviousSign = resultStack.top();//拿出栈顶元素                resultStack.pop();//弹出栈顶元素                result = result * priviousSign + resultStack.top();//将结果和之前的结果(当前栈顶元素)相加,算出新的结果                resultStack.pop();//将原来的结果弹出                sign = 1;            }        }//end for        return result;    }//end methods};//end class


0 0
原创粉丝点击