当前位置:网站首页>LeetCode_ Stack_ Medium_ 227. basic calculator II (without brackets)
LeetCode_ Stack_ Medium_ 227. basic calculator II (without brackets)
2022-06-30 14:01:00 【I've been up and down in the Jianghu】
1. subject
Here's a string expression for you s , Please implement a basic calculator to calculate and return its value . Division of integers preserves only the integral part .
You can assume that a given expression is always valid . All intermediate results will be in [-231, 231 - 1] Within the scope of .
Be careful : Any built-in functions that evaluate strings as mathematical expressions are not allowed , such as eval() .
Example 1:
Input :s = “3+2*2”
Output :7
Example 2:
Input :s = " 3/2 "
Output :1
Example 3:
Input :s = " 3+5 / 2 "
Output :5
Tips :
1 <= s.length <= 3 * 105
s By integers and operators (‘+’, ‘-’, ‘*’, ‘/’) form , The middle is separated by some spaces
s Represents a valid expression
All integers in an expression are nonnegative integers , And in scope [0, 231 - 1] Inside
The question data guarantees that the answer is 32-bit Integers
source : Power button (LeetCode)
link :https://leetcode.cn/problems/basic-calculator-ii
2. Ideas
(1) Stack
Analysis of the title shows that , The expression of this question does not contain brackets , So relatively speaking , Relatively simple .
The general idea is as follows : Because multiplication and division have higher priority than addition and subtraction , So let's do all the multiplication and division first , And put the result back to the corresponding position of the original expression , The result of adding and subtracting all remaining integers is the result of the original expression . In the process , You can use the stack to store these ( After multiplication and division ) The value of an integer . For the number after the plus and minus sign , Push it directly into the stack ; For the number after the multiplication and division sign , First calculate them with the top element of the stack, and then push them onto the stack ( Pay attention to the calculation order , Should be Top element of stack */ Current number ).
3. Code implementation (Java)
// Ideas 1———— Stack
class Solution {
public int calculate(String s) {
Stack<Integer> stack = new Stack<>();
int res = 0;
int length = s.length();
// Represents every number encountered while traversing an expression
int num = 0;
//sign Record the operator before each number , For the first number in the expression , The default operator is '+'
char sign = '+';
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
/* Because of the variable c It's a ASCII code , If you don't put brackets, you'll add and then subtract , If s The integer value of is very close to Integer.MAX_VALUE, May cause integer overflow , therefore (c - '0') Do not omit the parenthesis */
num = num * 10 + (c - '0');
}
if (!Character.isDigit(c) && c != ' ' || i == length - 1) {
switch (sign) {
case '+':
stack.push(num);
break;
case '-':
stack.push(-num);
break;
/* '*' and '/' The operation priority of is higher than '+' and '-' So when you meet '*' and '/' when , First count the numbers on both sides of them Carry out operations ( The number on the left is the stack top element , The number on the right is num), Then push the result onto the stack */
case '*':
stack.push(stack.pop() * num);
break;
case '/':
stack.push(stack.pop() / num);
break;
}
sign = c;
num = 0;
}
}
// Add all the elements in the stack , The final calculation result can be obtained
while (!stack.isEmpty()) {
res += stack.pop();
}
return res;
}
}
边栏推荐
- [redis series] redis learning 16. Redis Dictionary (map) and its core coding structure
- Defi "where does the money come from"? A problem that most people don't understand
- How does MySQL merge columns?
- 幸运哈希竞猜系统开发(源码部署)趣投哈希游戏玩法开发(案例需求)
- Basic syntax of unity script (5) - vector
- 【系统分析师之路】第五章 复盘软件工程(敏捷开发)
- Write, append, read, and copy of golang files: examples of using bufio packages
- 优思学院:六西格玛不只是统计!
- SQL attendance statistics monthly report
- [Title brushing] coco, who likes bananas
猜你喜欢

深入理解.Net中的线程同步之构造模式(二)内核模式4.内核模式构造物的总结

损失函数:DIOU loss手写实现

Methodology for troubleshooting problems (applicable to troubleshooting problems arising from any multi-party cooperation)
![[scientific research data processing] [basic] category variable frequency analysis chart, numerical variable distribution chart and normality test (including lognormal)](/img/70/8bf226964118efb324ca4d339df654.png)
[scientific research data processing] [basic] category variable frequency analysis chart, numerical variable distribution chart and normality test (including lognormal)

The programming competition is coming! B station surrounding, senior members and other good gifts to you!

More than 20 years after Hong Kong's return, Tupu digital twin Hong Kong Zhuhai Macao Bridge has shocked

Defi "where does the money come from"? A problem that most people don't understand

Apache Doris comparison optimization Encyclopedia

Loss function: Diou loss handwriting implementation

Embedded development: five C features that may no longer be prohibited
随机推荐
Basic syntax of unity script (3) - accessing game object components
Unity 频繁切换分支 结果模型出现莫名其妙的错误
numpy 创建空数组 data = np.empty(shape=[1, 64,64,3])
【系统分析师之路】第五章 复盘软件工程(敏捷开发)
I'd like to ask you, where can I open an account in Foshan? Is it safe to open a mobile account?
More than 20 years after Hong Kong's return, Tupu digital twin Hong Kong Zhuhai Macao Bridge has shocked
[deep anatomy of C language] storage principle of float variable in memory & comparison between pointer variable and "zero value"
深入理解.Net中的线程同步之构造模式(二)内核模式4.内核模式构造物的总结
QQ was stolen? The reason is
Today's sleep quality record 80 points
Inexplicable error occurred in unity's frequent switching branch result model
【Kubernetes系列】K8s设置MySQL8大小写不敏感
[Title brushing] avoid flooding
Step by step | help you easily submit Google play data security form
Heavyweight: the domestic ide was released, developed by Alibaba, and is completely open source!
When SQL queries are performed in table storage, an error is reported when the primary key is added to the query result, and the query result exceeds 10W rows. Do you want to add multiple indexes to t
Rpm2rpm packaging steps
重磅:国产IDE发布,由阿里研发,完全开源!
Basic syntax of unity script (1) - common operations of game objects
Golang template (text/template)