<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>calculator Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/calculator/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/calculator/</link>
	<description></description>
	<lastBuildDate>Tue, 10 Mar 2020 01:40:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>calculator Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/calculator/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 227. Basic Calculator II</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-227-basic-calculator-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-227-basic-calculator-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 10 Mar 2020 01:24:59 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[calculator]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6442</guid>

					<description><![CDATA[<p>Implement a basic calculator to evaluate a simple expression string. The expression string contains only&#160;non-negative&#160;integers,&#160;+,&#160;-,&#160;*,&#160;/&#160;operators and empty spaces&#160;. The integer division should truncate toward zero.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-227-basic-calculator-ii/">花花酱 LeetCode 227. Basic Calculator II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Implement a basic calculator to evaluate a simple expression string.</p>



<p>The expression string contains only&nbsp;<strong>non-negative</strong>&nbsp;integers,&nbsp;<code>+</code>,&nbsp;<code>-</code>,&nbsp;<code>*</code>,&nbsp;<code>/</code>&nbsp;operators and empty spaces&nbsp;. The integer division should truncate toward zero.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input: </strong>"3+2*2"
<strong>Output:</strong> 7
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> " 3/2 "
<strong>Output:</strong> 1</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> " 3+5 / 2 "
<strong>Output:</strong> 5
</pre>



<p><strong>Note:</strong></p>



<ul><li>You may assume that the given expression is always valid.</li><li><strong>Do not</strong>&nbsp;use the&nbsp;<code>eval</code>&nbsp;built-in library function.</li></ul>



<h2><strong>Solution: Stack</strong></h2>



<p>if operator is ‘+’ or ‘-’, push the current num * sign onto stack.<br>if operator &#8216;*&#8217; or &#8216;/&#8217;, pop the last num from stack and * or / by the current num and push it back to stack.</p>



<p>The answer is the sum of numbers on stack.</p>



<p>3+2*2 =&gt; {3}, {3,2}, {3, 2*2} = {3, 4} =&gt; ans = 7<br>3 +5/2 =&gt; {3}, {3,5}, {3, 5/2} = {3, 2} =&gt; ans = 5<br>1 + 2*3 &#8211; 5 =&gt; {1}, {1,2}, {1,2*3} = {1,6}, {1, 6, -5} =&gt; ans = 2</p>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int calculate(string s) {
    vector&lt;int&gt; nums;    
    char op = '+';
    int cur = 0;
    int pos = 0;
    while (pos &lt; s.size()) {
      if (s[pos] == ' ') {
        ++pos;
        continue;
      }
      while (isdigit(s[pos]) &amp;&amp; pos &lt; s.size())
        cur = cur * 10 + (s[pos++] - '0');      
      if (op == '+' || op == '-') {
        nums.push_back(cur * (op == '+' ? 1 : -1));
      } else if (op == '*') {
        nums.back() *= cur;
      } else if (op == '/') {
        nums.back() /= cur;
      }
      cur = 0;      
      op = s[pos++];
    }
    return accumulate(begin(nums), end(nums), 0);
  }
};</pre>
</div></div>



<div class="responsive-tabs">
<h2 class="tabtitle">python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def calculate(self, s: str) -&gt; int:
    nums = []
    op = '+'
    cur = 0
    i = 0
    while i &lt; len(s):
      if s[i] == ' ': 
        i += 1
        continue
      while i &lt; len(s) and s[i].isdigit():
        cur = cur * 10 + ord(s[i]) - ord('0')
        i += 1      
      if op in '+-':
        nums.append(cur * (1 if op == '+' else -1))
      elif op == '*':
        nums[-1] *= cur
      elif op == '/':
        sign = -1 if nums[-1] &lt; 0 or cur &lt; 0 else 1
        nums[-1] = abs(nums[-1]) // abs(cur) * sign
      cur = 0
      if (i &lt; len(s)): op = s[i]
      i += 1    
    return sum(nums)</pre>
</div></div>



<h2><strong>Related Problems</strong></h2>



<ul><li><a href="https://zxi.mytechroad.com/blog/recursion/leetcode-224-basic-calculator/">https://zxi.mytechroad.com/blog/recursion/leetcode-224-basic-calculator/</a></li><li><a href="https://zxi.mytechroad.com/blog/recursion/leetcode-736-parse-lisp-expression/">https://zxi.mytechroad.com/blog/recursion/leetcode-736-parse-lisp-expression/</a></li><li><a href="https://zxi.mytechroad.com/blog/searching/leetcode-282-expression-add-operators/">https://zxi.mytechroad.com/blog/searching/leetcode-282-expression-add-operators/</a></li></ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-227-basic-calculator-ii/">花花酱 LeetCode 227. Basic Calculator II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/stack/leetcode-227-basic-calculator-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 224. Basic Calculator</title>
		<link>https://zxi.mytechroad.com/blog/recursion/leetcode-224-basic-calculator/</link>
					<comments>https://zxi.mytechroad.com/blog/recursion/leetcode-224-basic-calculator/#comments</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 09 Mar 2020 20:33:55 +0000</pubDate>
				<category><![CDATA[Recursion]]></category>
		<category><![CDATA[calculator]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[recursion]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6438</guid>

					<description><![CDATA[<p>Implement a basic calculator to evaluate a simple expression string. The expression string may contain open&#160;(&#160;and closing parentheses&#160;), the plus&#160;+&#160;or minus sign&#160;-,&#160;non-negative&#160;integers and empty spaces&#160;.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-224-basic-calculator/">花花酱 LeetCode 224. Basic Calculator</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Implement a basic calculator to evaluate a simple expression string.</p>



<p>The expression string may contain open&nbsp;<code>(</code>&nbsp;and closing parentheses&nbsp;<code>)</code>, the plus&nbsp;<code>+</code>&nbsp;or minus sign&nbsp;<code>-</code>,&nbsp;<strong>non-negative</strong>&nbsp;integers and empty spaces&nbsp;.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> "1 + 1"
<strong>Output:</strong> 2
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> " 2-1 + 2 "
<strong>Output:</strong> 3</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23</pre>



<p><strong>Note:</strong></p>



<ul><li>You may assume that the given expression is always valid.</li><li><strong>Do not</strong>&nbsp;use the&nbsp;<code>eval</code>&nbsp;built-in library function.</li></ul>



<h2><strong>Solution: Recursion</strong></h2>



<p>Make a recursive call when there is an open parenthesis and return if there is close parenthesis.</p>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int calculate(string s) {    
    function&lt;int(int&amp;)&gt; eval = [&amp;](int&amp; pos) {
      int ret = 0;
      int sign = 1;
      int val = 0;
      while (pos &lt; s.size()) {
        const char ch = s[pos];
        if (isdigit(ch)) {
          val = val * 10 + (s[pos++] - '0');
        } else if (ch == '+' || ch == '-') {
          ret += sign * val;
          val = 0;
          sign = ch == '+' ? 1 : -1;
          ++pos;
        } else if (ch == '(') {
          val = eval(++pos);
        } else if (ch == ')') {          
          ++pos;
          break;
        } else {
          ++pos;
        }
      }
      return ret += sign * val;
    };
    int pos = 0;
    return eval(pos);
  }
};</pre>
</div></div>



<div class="responsive-tabs">
<h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def calculate(self, s: str) -&gt; int:
    self.pos = 0    
    def eval():
      val = 0
      sign = 1
      ret = 0
      while self.pos &lt; len(s):
        ch = s[self.pos]
        if ch == ' ':
          self.pos += 1
        elif ch == '(':
          self.pos += 1
          val = eval()
        elif ch == ')':
          self.pos += 1
          ret += sign * val
          return ret
        elif ch == '+' or ch == '-':
          ret += sign * val
          val = 0
          sign = 1 if ch == '+' else -1
          self.pos += 1
        else:
          val = val * 10 + (ord(ch) - ord('0'))
          self.pos += 1
      ret += val * sign
      return ret
    return eval()</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-224-basic-calculator/">花花酱 LeetCode 224. Basic Calculator</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/recursion/leetcode-224-basic-calculator/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
