The link to the original question is here :https://leetcode.com/problems/basic-calculator-ii/

subject :

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.

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

Note:

  • You may assume that the given expression is always valid.
  • Do not use the eval built-in library function.

Answer key :

It could apply the generic method. Use two level of operations. Calculate * and / first, accumlate the result into num2.

Then + and -, accumlate the result into num1.

When current char is digit, get the current number, perform * and /.

If current char is * and /, update operator 2.

If current char is + and -, perform previous + and - operation and update operator 1, reset num2, operator 2.

Time Complexity: O(n). n = s.length().

Space: O(1).

AC Java:

 class Solution {
public int calculate(String s) {
if(s == null || s.length() == 0){
return 0;
} int num1 = 0;
int o1 = 1;
int num2 = 1;
int o2 = 1;
for(int i = 0; i<s.length(); i++){
char c = s.charAt(i);
if(Character.isDigit(c)){
int cur = c - '0';
while(i+1 < s.length() && Character.isDigit(s.charAt(i+1))){
cur = cur * 10 + s.charAt(i+1)-'0';
i++;
} num2 = o2 == 1 ? num2 * cur : num2 / cur;
}else if(c == '*' || c == '/'){
o2 = c == '*' ? 1 : -1;
}else if(c == '+' || c == '-'){
num1 = num1 + o1 * num2;
o1 = c == '+' ? 1 : -1; num2 = 1;
o2 = 1;
}
} return num1 + o1 * num2;
}
}

similar Basic CalculatorBasic Calculator III.

LeetCode Basic Calculator II More articles about

  1. [LeetCode] Basic Calculator II Basic calculator two

    Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

  2. LeetCode——Basic Calculator II

    Description: Implement a basic calculator to evaluate a simple expression string. The expression str ...

  3. LeetCode 227. Basic calculator II(Basic Calculator II)

    227. Basic calculator II 227. Basic Calculator II Title Description Implement a basic calculator to calculate the value of a simple string expression . String expressions contain only nonnegative integers ,+,-,*,/ Four operators and ...

  4. leetcode 224. Basic Calculator 、227. Basic Calculator II

    This kind of question needs to set a variable of sign bit 224. Basic Calculator Set the numeric and symbolic variables , Add the value and symbol to the stack when the left bracket is encountered class Solution { public: int calcu ...

  5. 【LeetCode】227. Basic Calculator II

    Basic Calculator II Implement a basic calculator to evaluate a simple expression string. The express ...

  6. [LeetCode] Basic Calculator &amp; Basic Calculator II

    Basic Calculator Implement a basic calculator to evaluate a simple expression string. The expression ...

  7. LeetCode OJ Basic Calculator II

    Basic Calculator II subject Ideas Same as this one :Basic Calculator I Code class ExpressionTransformation { public: strin ...

  8. [LeetCode] Basic Calculator Basic calculator

    Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...

  9. LeetCode Basic Calculator

    The link to the original question is here :https://leetcode.com/problems/basic-calculator/ Implement a basic calculator to evaluate a s ...

Random recommendation

  1. vue.js Basic operation

    1.{{message}} Output data In the data message. 2.v-for="todo in todos" Output data In the data dotos Array 3.v-on:click=&quo ...

  2. 【 Code Notes 】iOS- Click the search button , Or after the magnifying glass will pop up the search box

    One , design sketch . Two , Engineering drawings . 3、 ... and , Code . RootViewController.h #import <UIKit/UIKit.h> #import "CLHSearchBar.h ...

  3. VerbalExpressions —— Alternative regular expressions

    For text processing , Regular expressions are undoubtedly a very powerful tool . But writing and reading regular expressions is often not a very pleasant thing . This article introduces another kind of regular expression ——VerbalExpressions, It takes the function ...

  4. ldconfig And LD_LIBRARY_PATH

    dconfig And  LD_LIBRARY_PATH 1. Go to /lib and /usr/lib There's something in it , No need to modify /etc/ld.so.conf Of , But after that, we need to adjust it ldconfig, Otherwise, this library ...

  5. Java Language guidance notes Chapter 9 IO

    java.io 9.1.1 Character stream Reader For the reader (reader) Provide API And partial implementation , The reader is reading 16 Bit character stream : Writer For the writer (writer) Provide API And partial implementation , The writer is to write 16 Bit words ...

  6. spring Resource loading instructions

    Spring Provides a powerful mechanism for loading resources , Not only can we pass “classpath:”.“file:” The resource address prefix identifies different resource types , And support Ant Style resource address with wildcards . First , Let's get to know Spri ...

  7. javascript Closure summary

    I read several books about closures , Feeling <JavaScript Object oriented programming guide > The book is the most clear , Many other books only focus on the results , Let's not talk about the specific reasons , Not easy to understand . Summarized below 1. Definition of closure If a function would be in ...

  8. Eclipse from GitHub Download code

    Reprinted from :http://blog.csdn.net/u014785687/article/details/73473769 open git View (window->show view), Search for git, choice G ...

  9. C# Realize real-time network speed

    Preface Recently participated in a project , So less time to blog , One function of the project is to display the real-time network speed on the form , It took half a day to write it out , Think about it. There's plenty of time today , Share it on your blog . Project presentation Project core code : private ...

  10. How to make wechat html Application pop up “ Click on the top right corner to share to the circle of friends ” Pictures of the

    A share button , A hidden picture ( This picture is definitely in the upper right corner ) And then click Show , Click to hide ... <a href="javascript:;" onclick="docu ...