Solving Basic Calculator I, II, III on leetcode

The questions look easy at first, it seems that we just need to do it as we what we learned from elementary school. But when we think clearly, it is not that easy. Due to the math rules, some numbers and some part of the blocks are to be calculated first, it is not that straight forward to do the math by just iterating from the left to the right at once.

Examples:Input: "1 + 1"
Return: 2
Input: " 2-1 + 2 "
Output: 3
Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23

what if we need to calculate +-*/ as well?

Examples:Input: "3+2*2" 
Return 7
Input: " 3/2 "
Return 1
Input: " 3+5 / 2 "
return: 5

OK, Let’s see what if we need ( and ) as well.

Examples:Input: "1 + 1" 
Return: 2
Input: " 6-4 / 2 "
Return: 4
Input: "2*(5+5*2)/3+(6/2+8)"
Return: 21
Input: "(2+6* 3+5- (3*14/7+2)*5)+3"
Return: -12

I hope it helps

By the way, if you are interested in algorithms, here is my journey on a daily challenge, AlgoDaily. I have also included the above questions in the repo, please feel free to take a look at it. Thank you.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store