Online Courses
Free Tutorials  Go to Your University  Placement Preparation 
Goeduhub's Online Courses @ Udemy in Just INR 570/-
Online Training - Youtube Live Class Link
0 like 0 dislike
202 views
in Coding Questions by Goeduhub's Expert (2.3k points)

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.

Goeduhub's Top Online Courses @Udemy

For Indian Students- INR 360/- || For International Students- $9.99/-

S.No.

Course Name

 Coupon

1.

Tensorflow 2 & Keras:Deep Learning & Artificial Intelligence

Apply Coupon

2.

Natural Language Processing-NLP with Deep Learning in Python Apply Coupon

3.

Computer Vision OpenCV Python | YOLO| Deep Learning in Colab Apply Coupon
    More Courses

1 Answer

0 like 0 dislike
by Goeduhub's Expert (2.3k points)
 
Best answer

Pretty easy with stack, we would add value into stack if we encounter +/ - and for mul / div we would modify the exsting value into the stack and it again into stack.

class Solution:

    def calculate(self, s):

        num, stack, sign = 0, [], "+"

        for i in range(len(s)):

            if s[i].isdigit():

                num = num * 10 + int(s[i])

            if s[i] in "+-*/" or i == len(s) - 1:

                if sign == "+":

                    stack.append(num)

                elif sign == "-":

                    stack.append(-num)

                elif sign == "*":

                    stack.append(stack.pop()*num)

                else:

                    stack.append(int(stack.pop()/num))

                num = 0

                sign = s[i]

        return sum(stack)

eg : ans = Solution()

ans.calculate("3+2*2")

Output -

7

3.3k questions

7.1k answers

394 comments

4.6k users

Related questions

0 like 0 dislike
1 answer 448 views
asked Sep 13, 2020 in Coding Questions by Vaibhav98 Goeduhub's Expert (2.3k points)
0 like 0 dislike
1 answer 481 views
0 like 0 dislike
1 answer 346 views
asked Sep 4, 2020 in Coding Questions by Vaibhav98 Goeduhub's Expert (2.3k points)
0 like 0 dislike
1 answer 1k views
0 like 0 dislike
1 answer 172 views
asked Aug 29, 2020 in Coding Questions by Vaibhav98 Goeduhub's Expert (2.3k points)

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy || Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 
...