LeetCode 227 Basic Calculator II

简介: 版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/51337819 ...
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/51337819

原文

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces .

The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

Note: Do not use the eval built-in library function.

翻译

使用一个基本的计算器来计算一个简单的字符串表达式。

该字符串表达式仅仅包含非负的整型数,+,-,*,/操作符和空格。

数字相除都向0取整。

你可以假定给定的表达式是合法的。

不要使用内建的库函数。

代码

每当在内部的for循环结束之后,i已经多加了1,例如“21*2”,遍历出数字21后,i为2,正好是op的值。

int calculate(string s) {
    int result = 0, num = 0, temp = 0;
    char op = '+';
    for (int i = 0; i < s.size(); i++) {
        if (isdigit(s[i])) {
            num = 0;
            for (;i < s.size() && isdigit(s[i]); i++) {
                num = num * 10 + s[i] - '0';
            }
            if (op == '+' || op == '-') {
                result += temp;
                temp = num * (op == '-' ? -1 : 1);
            } else if (op == '*') {
                temp *= num;
            } else if (op == '/') {
                temp /= num;
            }
        }
        if (s[i] != ' ') {
            op = s[i];
        }
    }
    result += temp;
    return result;
}
目录
相关文章
|
存储
LeetCode 227. Basic Calculator II
实现一个基本的计算器来计算一个简单的字符串表达式的值。 字符串表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格 。 整数除法仅保留整数部分。
40 0
LeetCode 227. Basic Calculator II
Leetcode [224] Basic Calculator 基于语法树的解法
通过生成语法树,解决表达式求值问题
250 0
[LeetCode] Basic Calculator II
The basic idea of is as follows: Maintain a deque operands for the numbers and another deque operations for the operators +, -, *,/`.
658 0
|
26天前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
1月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
1月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3
|
1月前
|
容器
《LeetCode》——LeetCode刷题日记1
《LeetCode》——LeetCode刷题日记1
|
1月前
|
存储
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
143 38

热门文章

最新文章