<?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>conversion Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/conversion/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/conversion/</link>
	<description></description>
	<lastBuildDate>Mon, 29 Nov 2021 03:46:04 +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>conversion Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/conversion/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 171. Excel Sheet Column Number</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-171-excel-sheet-column-number/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-171-excel-sheet-column-number/#comments</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Nov 2021 22:35:07 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[math]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8884</guid>

					<description><![CDATA[<p>Given a string&#160;columnTitle&#160;that represents the column title as appear in an Excel sheet, return&#160;its corresponding column number. For example: A -> 1 B -> 2&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-171-excel-sheet-column-number/">花花酱 LeetCode 171. Excel Sheet Column Number</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>Given a string&nbsp;<code>columnTitle</code>&nbsp;that represents the column title as appear in an Excel sheet, return&nbsp;<em>its corresponding column number</em>.</p>



<p>For example:</p>



<pre class="wp-block-preformatted;crayon:false">A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28 
...
</pre>



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



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> columnTitle = "AB"
<strong>Output:</strong> 28
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> columnTitle = "ZY"
<strong>Output:</strong> 701
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> columnTitle = "FXSHRXW"
<strong>Output:</strong> 2147483647
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= columnTitle.length &lt;= 7</code></li><li><code>columnTitle</code>&nbsp;consists only of uppercase English letters.</li><li><code>columnTitle</code>&nbsp;is in the range&nbsp;<code>["A", "FXSHRXW"]</code>.</li></ul>



<h2><strong>Solution: Base conversion</strong></h2>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int titleToNumber(string s) {
    int ans = 0;    
    for (int i = s.length() - 1, cur = 0; i &amp;gt;= 0; --i) {
      cur = cur ? cur * 26 : 1;
      ans += (s[i] - 'A' + 1) * cur;
    }
    return ans;
  }
};</pre>
</div></div>



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



<ul><li><a href="https://zxi.mytechroad.com/blog/math/leetcode-168-excel-sheet-column-title/" data-type="post">花花酱 LeetCode 168. Excel Sheet Column Title</a></li></ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-171-excel-sheet-column-number/">花花酱 LeetCode 171. Excel Sheet Column Number</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/math/leetcode-171-excel-sheet-column-number/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1880. Check if Word Equals Summation of Two Words</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1880-check-if-word-equals-summation-of-two-words/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1880-check-if-word-equals-summation-of-two-words/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Aug 2021 23:01:45 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8520</guid>

					<description><![CDATA[<p>The&#160;letter value&#160;of a letter is its position in the alphabet&#160;starting from 0&#160;(i.e.&#160;'a' -&#62; 0,&#160;'b' -&#62; 1,&#160;'c' -&#62; 2, etc.). The&#160;numerical value&#160;of some string of lowercase&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1880-check-if-word-equals-summation-of-two-words/">花花酱 LeetCode 1880. Check if Word Equals Summation of Two Words</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>The&nbsp;<strong>letter value</strong>&nbsp;of a letter is its position in the alphabet&nbsp;<strong>starting from 0</strong>&nbsp;(i.e.&nbsp;<code>'a' -&gt; 0</code>,&nbsp;<code>'b' -&gt; 1</code>,&nbsp;<code>'c' -&gt; 2</code>, etc.).</p>



<p>The&nbsp;<strong>numerical value</strong>&nbsp;of some string of lowercase English letters&nbsp;<code>s</code>&nbsp;is the&nbsp;<strong>concatenation</strong>&nbsp;of the&nbsp;<strong>letter values</strong>&nbsp;of each letter in&nbsp;<code>s</code>, which is then&nbsp;<strong>converted</strong>&nbsp;into an integer.</p>



<ul><li>For example, if&nbsp;<code>s = "acb"</code>, we concatenate each letter&#8217;s letter value, resulting in&nbsp;<code>"021"</code>. After converting it, we get&nbsp;<code>21</code>.</li></ul>



<p>You are given three strings&nbsp;<code>firstWord</code>,&nbsp;<code>secondWord</code>, and&nbsp;<code>targetWord</code>, each consisting of lowercase English letters&nbsp;<code>'a'</code>&nbsp;through&nbsp;<code>'j'</code>&nbsp;<strong>inclusive</strong>.</p>



<p>Return&nbsp;<code>true</code>&nbsp;<em>if the&nbsp;<strong>summation</strong>&nbsp;of the&nbsp;<strong>numerical values</strong>&nbsp;of&nbsp;</em><code>firstWord</code><em>&nbsp;and&nbsp;</em><code>secondWord</code><em>&nbsp;equals the&nbsp;<strong>numerical value</strong>&nbsp;of&nbsp;</em><code>targetWord</code><em>, or&nbsp;</em><code>false</code><em>&nbsp;otherwise.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> firstWord = "acb", secondWord = "cba", targetWord = "cdb"
<strong>Output:</strong> true
<strong>Explanation:</strong>
The numerical value of firstWord is "acb" -&gt; "021" -&gt; 21.
The numerical value of secondWord is "cba" -&gt; "210" -&gt; 210.
The numerical value of targetWord is "cdb" -&gt; "231" -&gt; 231.
We return true because 21 + 210 == 231.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> firstWord = "aaa", secondWord = "a", targetWord = "aab"
<strong>Output:</strong> false
<strong>Explanation:</strong> 
The numerical value of firstWord is "aaa" -&gt; "000" -&gt; 0.
The numerical value of secondWord is "a" -&gt; "0" -&gt; 0.
The numerical value of targetWord is "aab" -&gt; "001" -&gt; 1.
We return false because 0 + 0 != 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> firstWord = "aaa", secondWord = "a", targetWord = "aaaa"
<strong>Output:</strong> true
<strong>Explanation:</strong> 
The numerical value of firstWord is "aaa" -&gt; "000" -&gt; 0.
The numerical value of secondWord is "a" -&gt; "0" -&gt; 0.
The numerical value of targetWord is "aaaa" -&gt; "0000" -&gt; 0.
We return true because 0 + 0 == 0.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= firstWord.length,&nbsp;secondWord.length,&nbsp;targetWord.length &lt;= 8</code></li><li><code>firstWord</code>,&nbsp;<code>secondWord</code>, and&nbsp;<code>targetWord</code>&nbsp;consist of lowercase English letters from&nbsp;<code>'a'</code>&nbsp;to&nbsp;<code>'j'</code>&nbsp;<strong>inclusive</strong>.</li></ul>



<h2><strong>Solution: Brute Force</strong></h2>



<p>Tips: Write a reusable function to compute the score of a word.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool isSumEqual(string firstWord, string secondWord, string targetWord) {
    auto score = [](string_view s) {
      int ans = 0;
      for (char c : s)
        ans = ans * 10 + (c - 'a');
      return ans;
    };
    return score(firstWord) + score(secondWord) == score(targetWord);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1880-check-if-word-equals-summation-of-two-words/">花花酱 LeetCode 1880. Check if Word Equals Summation of Two Words</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/string/leetcode-1880-check-if-word-equals-summation-of-two-words/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1742. Maximum Number of Balls in a Box</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1742-maximum-number-of-balls-in-a-box/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1742-maximum-number-of-balls-in-a-box/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 31 Jan 2021 04:31:10 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[base10]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8045</guid>

					<description><![CDATA[<p>You are working in a ball factory where you have&#160;n&#160;balls numbered from&#160;lowLimit&#160;up to&#160;highLimit&#160;inclusive&#160;(i.e.,&#160;n == highLimit - lowLimit + 1), and an infinite number of boxes&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1742-maximum-number-of-balls-in-a-box/">花花酱 LeetCode 1742. Maximum Number of Balls in a Box</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>You are working in a ball factory where you have&nbsp;<code>n</code>&nbsp;balls numbered from&nbsp;<code>lowLimit</code>&nbsp;up to&nbsp;<code>highLimit</code>&nbsp;<strong>inclusive</strong>&nbsp;(i.e.,&nbsp;<code>n == highLimit - lowLimit + 1</code>), and an infinite number of boxes numbered from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>infinity</code>.</p>



<p>Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball&#8217;s number. For example, the ball number&nbsp;<code>321</code>&nbsp;will be put in the box number&nbsp;<code>3 + 2 + 1 = 6</code>&nbsp;and the ball number&nbsp;<code>10</code>&nbsp;will be put in the box number&nbsp;<code>1 + 0 = 1</code>.</p>



<p>Given two integers&nbsp;<code>lowLimit</code>&nbsp;and&nbsp;<code>highLimit</code>, return<em>&nbsp;the number of balls in the box with the most balls.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> lowLimit = 1, highLimit = 10
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Box Number:  1 2 3 4 5 6 7 8 9 10 11 ...
Ball Count:  2 1 1 1 1 1 1 1 1 0  0  ...
Box 1 has the most number of balls with 2 balls.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> lowLimit = 5, highLimit = 15
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Box Number:  1 2 3 4 5 6 7 8 9 10 11 ...
Ball Count:  1 1 1 1 2 2 1 1 1 0  0  ...
Boxes 5 and 6 have the most number of balls with 2 balls in each.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> lowLimit = 19, highLimit = 28
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Box Number:  1 2 3 4 5 6 7 8 9 10 11 12 ...
Ball Count:  0 1 1 1 1 1 1 1 1 2  0  0  ...
Box 10 has the most number of balls with 2 balls.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= lowLimit &lt;= highLimit &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Hashtable and base-10</strong></h2>



<p>Max sum will be 9+9+9+9+9 = 45</p>



<p>Time complexity: O((hi-lo) * log(hi))<br>Space complexity: O(1)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int countBalls(int lowLimit, int highLimit) {
    vector&lt;int&gt; balls(46);
    int ans = 0;
    for (int i = lowLimit; i &lt;= highLimit; ++i) {
      int n = i;
      int box = 0;
      while (n) { box += n % 10; n /= 10; }
      ans = max(ans, ++balls[box]);
    }
    return ans;
  }
};</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def countBalls(self, lowLimit: int, highLimit: int) -&gt; int:
    balls = defaultdict(int)
    ans = 0
    for x in range(lowLimit, highLimit + 1):
      s = sum(int(d) for d in str(x))
      balls[s] += 1
      ans = max(ans, balls[s])
    return ans</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1742-maximum-number-of-balls-in-a-box/">花花酱 LeetCode 1742. Maximum Number of Balls in a Box</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/hashtable/leetcode-1742-maximum-number-of-balls-in-a-box/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 165. Compare Version Numbers</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-165-compare-version-numbers/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-165-compare-version-numbers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 09 Mar 2020 08:06:39 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[dot]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6435</guid>

					<description><![CDATA[<p>Compare two version numbers&#160;version1&#160;and&#160;version2.If&#160;version1&#160;&#62;&#160;version2&#160;return&#160;1;&#160;if&#160;version1&#160;&#60;&#160;version2&#160;return&#160;-1;otherwise return&#160;0. You may assume that the version strings are non-empty and contain only digits and the&#160;.&#160;character. The&#160;.&#160;character does not represent a&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-165-compare-version-numbers/">花花酱 LeetCode 165. Compare Version Numbers</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>Compare two version numbers&nbsp;<em>version1</em>&nbsp;and&nbsp;<em>version2</em>.<br>If&nbsp;<code><em>version1</em>&nbsp;&gt;&nbsp;<em>version2</em></code>&nbsp;return&nbsp;<code>1;</code>&nbsp;if&nbsp;<code><em>version1</em>&nbsp;&lt;&nbsp;<em>version2</em></code>&nbsp;return&nbsp;<code>-1;</code>otherwise return&nbsp;<code>0</code>.</p>



<p>You may assume that the version strings are non-empty and contain only digits and the&nbsp;<code>.</code>&nbsp;character.</p>



<p>The&nbsp;<code>.</code>&nbsp;character does not represent a decimal point and is used to separate number sequences.</p>



<p>For instance,&nbsp;<code>2.5</code>&nbsp;is not &#8220;two and a half&#8221; or &#8220;half way to version three&#8221;, it is the fifth second-level revision of the second first-level revision.</p>



<p>You may assume the default revision number for each level of a version number to be&nbsp;<code>0</code>. For example, version number&nbsp;<code>3.4</code>&nbsp;has a revision number of&nbsp;<code>3</code>&nbsp;and&nbsp;<code>4</code>&nbsp;for its first and second level revision number. Its third and fourth level revision number are both&nbsp;<code>0</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> <code><em>version1</em></code> = "0.1", <code><em>version2</em></code> = "1.1"
<strong>Output:</strong> -1</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input: </strong><code><em>version1</em></code> = "1.0.1", <code><em>version2</em></code> = "1"
<strong>Output:</strong> 1</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> <code><em>version1</em></code> = "7.5.2.4", <code><em>version2</em></code> = "7.5.3"
<strong>Output:</strong> -1</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> <code><em>version1</em></code> = "1.01", <code><em>version2</em></code> = "1.001"
<strong>Output:</strong> 0
<strong>Explanation:</strong> Ignoring leading zeroes, both “01” and “001" represent the same number “1”</pre>



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> <code><em>version1</em></code> = "1.0", <code><em>version2</em></code> = "1.0.0"
<strong>Output:</strong> 0
<strong>Explanation:</strong> The first version number does not have a third level revision number, which means its third level revision number is default to "0"</pre>



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



<ol><li>Version strings are composed of numeric strings separated by dots&nbsp;<code>.</code>&nbsp;and this numeric strings&nbsp;<strong>may</strong>&nbsp;have leading zeroes.</li><li>Version strings do not start or end with dots, and they will not be two consecutive dots.</li></ol>



<p>Solution: String</p>



<p>Split the version string to a list of numbers, and compare two lists.</p>



<p>Time complexity: O(l1 + l2)<br>Space complexity: O(l1 + l2)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int compareVersion(string version1, string version2) {
    const auto&amp; v1 = parseVersion(version1);
    const auto&amp; v2 = parseVersion(version2);
    int i1 = 0, i2 = 0;
    while (i1 &lt; v1.size() || i2 &lt; v2.size()) {    
      int n1 = i1 &lt; v1.size() ? v1[i1++] : 0;
      int n2 = i2 &lt; v2.size() ? v2[i2++] : 0;
      if (n1 &lt; n2) return -1;
      else if (n1 &gt; n2) return 1;
    }
    return 0;
  }
private:
  vector&lt;int&gt; parseVersion(const string&amp; version) {
    vector&lt;int&gt; v;
    int s = 0;
    for (char c : version) {
      if (c == '.') {
        v.push_back(s);
        s = 0;
      } else {
        s = s * 10 + (c - '0');
      }
    }
    v.push_back(s);
    return v;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-165-compare-version-numbers/">花花酱 LeetCode 165. Compare Version Numbers</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/string/leetcode-165-compare-version-numbers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1271. Hexspeak</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1271-hexspeak/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1271-hexspeak/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 01 Dec 2019 04:18:40 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hex]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5890</guid>

					<description><![CDATA[<p>A decimal number can be converted to its&#160;Hexspeak representation&#160;by first converting it to an uppercase hexadecimal string, then replacing all occurrences of the digit&#160;0&#160;with the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1271-hexspeak/">花花酱 LeetCode 1271. Hexspeak</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>A decimal number can be converted to its&nbsp;<em>Hexspeak representation</em>&nbsp;by first converting it to an uppercase hexadecimal string, then replacing all occurrences of the digit&nbsp;<code>0</code>&nbsp;with the letter&nbsp;<code>O</code>, and the digit&nbsp;<code>1</code>&nbsp;with the letter&nbsp;<code>I</code>.&nbsp; Such a representation&nbsp;is&nbsp;<em>valid</em>&nbsp;if and only if it consists only of the letters in the set&nbsp;<code>{"A", "B", "C", "D", "E", "F", "I", "O"}</code>.</p>



<p>Given a string&nbsp;<code>num</code>&nbsp;representing a decimal integer&nbsp;<code>N</code>, return the Hexspeak representation of&nbsp;<code>N</code>&nbsp;if it is valid, otherwise return&nbsp;<code>"ERROR"</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "257"
<strong>Output:</strong> "IOI"
<strong>Explanation: </strong> 257 is 101 in hexadecimal.
</pre>



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



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



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= N &lt;= 10^12</code></li><li>There are no leading zeros in the given string.</li><li>All answers must be in uppercase letters.</li></ul>



<h2><strong>Solution: Simulation</strong></h2>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string toHexspeak(string num) {
    long n = stol(num);
    string ans;
    while (n) {
      int r = n % 16;
      char c;
      if (r == 0) c = 'O';
      else if (r == 1) c = 'I';
      else if (r &gt;= 10 &amp;&amp; r &lt;= 15) c = 'A' + r - 10;
      else return &quot;ERROR&quot;;
      ans += c;
      n &gt;&gt;= 4;
    }
    reverse(begin(ans), end(ans));
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1271-hexspeak/">花花酱 LeetCode 1271. Hexspeak</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/simulation/leetcode-1271-hexspeak/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 13. Roman to Integer</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-13-roman-to-integer/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-13-roman-to-integer/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 19 Sep 2018 15:39:39 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[roman]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4036</guid>

					<description><![CDATA[<p>Problem Roman numerals are represented by seven different symbols:&#160;I,&#160;V,&#160;X,&#160;L,&#160;C,&#160;D&#160;and&#160;M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-13-roman-to-integer/">花花酱 LeetCode 13. Roman to Integer</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 13. Roman to Integer - 刷题找工作 EP299" width="500" height="375" src="https://www.youtube.com/embed/joFpSO_sHnU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>


<h1><strong>Problem</strong></h1>
<p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>,&nbsp;<code>V</code>,&nbsp;<code>X</code>,&nbsp;<code>L</code>,&nbsp;<code>C</code>,&nbsp;<code>D</code>&nbsp;and&nbsp;<code>M</code>.</p>
<pre class="crayon:false"><strong>Symbol</strong>       <strong>Value</strong>
I             1
V             5
X             10
L             50
C             100
D             500
M             1000</pre>
<p>For example,&nbsp;two is written as&nbsp;<code>II</code>&nbsp;in Roman numeral, just two one&#8217;s added together. Twelve is written as,&nbsp;<code>XII</code>, which is simply&nbsp;<code>X</code>&nbsp;+&nbsp;<code>II</code>. The number twenty seven is written as&nbsp;<code>XXVII</code>, which is&nbsp;<code>XX</code>&nbsp;+&nbsp;<code>V</code>&nbsp;+&nbsp;<code>II</code>.</p>
<p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not&nbsp;<code>IIII</code>. Instead, the number four is written as&nbsp;<code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as&nbsp;<code>IX</code>. There are six instances where subtraction is used:</p>
<ul>
<li><code>I</code>&nbsp;can be placed before&nbsp;<code>V</code>&nbsp;(5) and&nbsp;<code>X</code>&nbsp;(10) to make 4 and 9.</li>
<li><code>X</code>&nbsp;can be placed before&nbsp;<code>L</code>&nbsp;(50) and&nbsp;<code>C</code>&nbsp;(100) to make 40 and 90.</li>
<li><code>C</code>&nbsp;can be placed before&nbsp;<code>D</code>&nbsp;(500) and&nbsp;<code>M</code>&nbsp;(1000) to make 400 and 900.</li>
</ul>
<p>Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input:</strong>&nbsp;"III"
<strong>Output:</strong> 3</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input:</strong>&nbsp;"IV"
<strong>Output:</strong> 4</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input:</strong>&nbsp;"IX"
<strong>Output:</strong> 9</pre>
<p><strong>Example 4:</strong></p>
<pre class="crayon:false"><strong>Input:</strong>&nbsp;"LVIII"
<strong>Output:</strong> 58
<strong>Explanation:</strong> C = 100, L = 50, XXX = 30 and III = 3.
</pre>
<p><strong>Example 5:</strong></p>
<pre class="crayon:false"><strong>Input:</strong>&nbsp;"MCMXCIV"
<strong>Output:</strong> 1994
<strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4.</pre>
<h1><strong>Solution</strong></h1>
<p>accumulate the value of each letter.</p>
<p>If the value of current letter is greater than the previous one, deduct twice of the previous value.</p>
<p>e.g. IX, 1 + 10 &#8211; 2 * 1 = 9 instead of 1 + 10 = 11</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int romanToInt(string s) {
    map&lt;char, int&gt; m{{'I', 1}, {'V', 5}, 
                     {'X', 10}, {'L', 50},
                     {'C', 100}, {'D', 500},
                     {'M', 1000}};
    int ans = 0;
    for (int i = 0; i &lt; s.length(); i++) {
      ans += m[s[i]];
      if (i &gt; 0 &amp;&amp; m[s[i]] &gt; m[s[i - 1]])
        ans -= 2 * m[s[i - 1]];
    }
    return ans;
  }
};</pre>

</div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
  private int v(char R) {
    switch (R) {
      case 'I' : return 1;
      case 'V' : return 5;
      case 'X' : return 10;
      case 'L' : return 50;
      case 'C' : return 100;
      case 'D' : return 500;
      case 'M' : return 1000;
      default: break;
    }
    return 0;
  }
  
  public int romanToInt(String s) {
    int ans = 0;
    for (int i = 0; i &lt; s.length(); i++) {
      ans += v(s.charAt(i));
      if ( i &gt; 0 &amp;&amp; v(s.charAt(i)) &gt; v(s.charAt(i - 1)))        
          ans -= 2 * v(s.charAt(i - 1));        
    }
    return ans;
  }
}</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class Solution:
  def romanToInt(self, s):
    m = {'I' : 1, 'V': 5, 'X': 10, 'L' : 50,
         'C' : 100, 'D': 500, 'M': 1000}
    ans = m[s[0]]
    for c, p in zip(s[1:], s[0:-1]):
      ans += m[c]
      if m[c] &gt; m[p]: ans -= 2 * m[p]
    return ans</pre>
</div></div><p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-13-roman-to-integer/">花花酱 LeetCode 13. Roman to Integer</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/string/leetcode-13-roman-to-integer/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 12. Integer to Roman</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-12-integer-to-roman/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-12-integer-to-roman/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 13 Sep 2018 03:18:07 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[roman]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3940</guid>

					<description><![CDATA[<p>Problem Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-12-integer-to-roman/">花花酱 LeetCode 12. Integer to Roman</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Roman numerals are represented by seven different symbols: <code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p>
<pre class="crayon:false"><strong>Symbol</strong>       <strong>Value</strong>
I             1
V             5
X             10
L             50
C             100
D             500
M             1000</pre>
<p>For example, two is written as <code>II</code> in Roman numeral, just two one&#8217;s added together. Twelve is written as, <code>XII</code>, which is simply <code>X</code> + <code>II</code>. The number twenty seven is written as <code>XXVII</code>, which is <code>XX</code> + <code>V</code> + <code>II</code>.</p>
<p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p>
<ul>
<li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.</li>
<li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.</li>
<li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li>
</ul>
<p>Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> 3
<strong>Output:</strong> "III"</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> 4
<strong>Output:</strong> "IV"</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> 9
<strong>Output:</strong> "IX"</pre>
<p><strong>Example 4:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> 58
<strong>Output:</strong> "LVIII"
<strong>Explanation:</strong> C = 100, L = 50, XXX = 30 and III = 3.
</pre>
<p><strong>Example 5:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> 1994
<strong>Output:</strong> "MCMXCIV"
<strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4.</pre>
<h1><strong>Solution: HashTable + Simulation</strong></h1>
<p>Map integer 1,4,5,9,10,40,50,90, &#8230;, 1000 to Romain</p>
<p>Start from the largest number y,</p>
<p>if x &gt;= y:<br />
ans += Roman[y]<br />
x -= y</p>
<p>Time complexity: O(x)</p>
<p>Space complexity: O(x)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string intToRoman(int num) {
    vector&lt;pair&lt;int,string&gt;&gt; v{{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"},
                               { 100, "C"}, { 90, "XC"}, { 50, "L"}, { 40, "XL"}, 
                               {  10, "X"}, {  9, "IX"}, {  5, "V"}, {  4, "IV"}, 
                               {   1, "I"}};
    string ans;
    auto it = cbegin(v);
    while (num) {
      if (num &gt;= it-&gt;first) {
        num -= it-&gt;first;
        ans += it-&gt;second;
      } else {
        ++it;
      }
    }
    return ans;
  }
};</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def intToRoman(self, num):
    m = [[1000, "M"], [900, "CM"], [500, "D"], [400, "CD"],
         [ 100, "C"], [ 90, "XC"], [ 50, "L"], [ 40, "XL"], 
         [  10, "X"], [  9, "IX"], [  5, "V"], [  4, "IV"], 
         [   1, "I"]]    
    index = 0
    ans = ''
    while num &gt; 0:
      if num &gt;= m[index][0]:
        ans += m[index][1]
        num -= m[index][0]
      else:
        index += 1
    return ans</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-12-integer-to-roman/">花花酱 LeetCode 12. Integer to Roman</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/simulation/leetcode-12-integer-to-roman/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 8. String to Integer (atoi)</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-8-string-to-integer-atoi/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-8-string-to-integer-atoi/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 12 Sep 2018 16:37:00 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[atoi]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[overflow]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3931</guid>

					<description><![CDATA[<p>Problem Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-8-string-to-integer-atoi/">花花酱 LeetCode 8. String to Integer (atoi)</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Implement <code>atoi</code> which converts a string to an integer.</p>
<p>The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.</p>
<p>The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.</p>
<p>If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.</p>
<p>If no valid conversion could be performed, a zero value is returned.</p>
<p><strong>Note:</strong></p>
<ul>
<li>Only the space character <code>' '</code> is considered as whitespace character.</li>
<li>Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2<sup>31</sup>,  2<sup>31 </sup>− 1]. If the numerical value is out of the range of representable values, INT_MAX (2<sup>31 </sup>− 1) or INT_MIN (−2<sup>31</sup>) is returned.</li>
</ul>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "42"
<strong>Output:</strong> 42
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "   -42"
<strong>Output:</strong> -42
<strong>Explanation:</strong> The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.
</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "4193 with words"
<strong>Output:</strong> 4193
<strong>Explanation:</strong> Conversion stops at digit '3' as the next character is not a numerical digit.
</pre>
<p><strong>Example 4:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "words and 987"
<strong>Output:</strong> 0
<strong>Explanation:</strong> The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.</pre>
<p><strong>Example 5:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "-91283472332"
<strong>Output:</strong> -2147483648
<strong>Explanation:</strong> The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−2<sup>31</sup>) is returned.</pre>
<h1><strong>Solution: Simulation</strong></h1>
<p>You need to handle all corner cases in order to pass&#8230;</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int myAtoi(const string&amp; s) {
    long long ans = 0;
    int neg = 0;
    int pos = 0;
    bool p = false; // has '.'
    bool a = false; // has letters
    bool n = false; // has number
    for (int i = 0; i &lt; s.length(); ++i) {      
      if (s[i] == ' ') { if (n || neg || pos) break; }
      else if (s[i] == '-') { if (n) break; else neg++; }
      else if (s[i] == '+') { if (n) break; else pos++; }
      else if (s[i] == '.') p = true;
      else if (s[i] &gt;= '0' &amp;&amp; s[i] &lt;= '9' &amp;&amp; !p &amp;&amp; !a) {
        ans = ans * 10 + (s[i] - '0');
        n = true;
      } else {
        a = true;
      }
      if (ans / 10 &gt; INT_MAX) break; // ans can be &gt; 64 bit
    }

    if (neg) ans = -ans;

    if (ans &gt; INT_MAX) ans = INT_MAX;
    if (ans &lt; INT_MIN) ans = INT_MIN;

    if (pos + neg &gt; 1) ans = 0;

    return ans;
  }
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-8-string-to-integer-atoi/">花花酱 LeetCode 8. String to Integer (atoi)</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/simulation/leetcode-8-string-to-integer-atoi/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 7. Reverse Integer</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-7-reverse-integer/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-7-reverse-integer/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 12 Sep 2018 16:14:16 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3927</guid>

					<description><![CDATA[<p>Problem Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-7-reverse-integer/">花花酱 LeetCode 7. Reverse Integer</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given a 32-bit signed integer, reverse digits of an integer.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> 123
<strong>Output:</strong> 321
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> -123
<strong>Output:</strong> -321
</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> 120
<strong>Output:</strong> 21
</pre>
<p><strong>Note:</strong><br />
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2<sup>31</sup>,  2<sup>31 </sup>− 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.</p>
<h1><strong>Solution: Simulation</strong></h1>
<p>Reverse digit by digit. Be careful about the overflow and negative numbers (especially in Python)</p>
<p>Time complexity: O(log(x)) ~ O(1)</p>
<p>Space complexity: O(log(x)) ~ O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int reverse(int x) {
    int ans = 0;
    while (x != 0) {
      int r = x % 10;
      if (ans &gt; INT_MAX / 10 || ans &lt; INT_MIN / 10) return 0;
      ans = ans * 10 + r;
      x /= 10;
    }
    return ans;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">class Solution {
  public int reverse(int x) {
    int ans = 0;
    while (x != 0) {
      int r = x % 10;
      if (ans &gt; Integer.MAX_VALUE / 10 || ans &lt; Integer.MIN_VALUE / 10) return 0;
      ans = ans * 10 + r;
      x /= 10;
    }
    return ans;
  }
}</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">class Solution:
  def reverse(self, x):
    min_val = -(2**31);
    max_val = 2**31 - 1;
    sign = -1 if x &lt; 0 else 1
    x = abs(x)
    ans = 0
    while x != 0:            
      ans = ans * 10 + (x % 10)
      x //= 10
    ans *= sign
    if ans &gt; max_val or ans &lt; min_val: return 0
    return ans</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-7-reverse-integer/">花花酱 LeetCode 7. Reverse Integer</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/simulation/leetcode-7-reverse-integer/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 6. ZigZag Conversion</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-6-zigzag-conversion/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-6-zigzag-conversion/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 12 Sep 2018 15:54:49 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[row]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[zigzag]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3923</guid>

					<description><![CDATA[<p>Problem The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-6-zigzag-conversion/">花花酱 LeetCode 6. ZigZag Conversion</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>The string <code>"PAYPALISHIRING"</code> is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)</p>
<pre class="crayon:false">P   A   H   N
A P L S I I G
Y   I   R
</pre>
<p>And then read line by line: <code>"PAHNAPLSIIGYIR"</code></p>
<p>Write the code that will take a string and make this conversion given a number of rows:</p>
<pre class="crayon:false">string convert(string s, int numRows);</pre>
<p><strong>Example 1:</strong><br />
&lt;preclass=&#8221;crayon:false&#8221;&gt;<strong>Input:</strong> s = &#8220;PAYPALISHIRING&#8221;, numRows = 3 <strong>Output:</strong> &#8220;PAHNAPLSIIGYIR&#8221;</p>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> s = "PAYPALISHIRING", numRows = 4
<strong>Output:</strong> "PINALSIGYAHRPI"
<strong>Explanation:</strong>

P     I    N
A   L S  I G
Y A   H R
P     I</pre>
<h1><strong>Solution: Simulation</strong></h1>
<p>Store the zigzag results for each row and then output row by row.</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string convert(string s, int nRows) {
    if (nRows == 1) return s;

    vector&lt;string&gt; ss(nRows);
    int l = s.length();
    int x = 0, y = 0, i = 0;
    bool down = true;
    while (i &lt; l) {
      ss[y] += s[i];
      if (down) {
        ++y;
        if (y == nRows) {
            down = false;
            y -=2;
        }
      } else {
        --y;
        if (y &lt; 0) {
            down = true;
            y = 1;
        }
      }
      i++;
    }

    string ans;
    for(const string&amp; r : ss)
      ans += r;
    return ans;
  }
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-6-zigzag-conversion/">花花酱 LeetCode 6. ZigZag Conversion</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/simulation/leetcode-6-zigzag-conversion/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 504. Base 7</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-504-base-7/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-504-base-7/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 17 Aug 2018 16:03:08 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[base]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3571</guid>

					<description><![CDATA[<p>Problem Given an integer, return its base 7 string representation. Example 1: Input: 100 Output: "202" Example 2: Input: -7 Output: "-10" Note: The input will&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-504-base-7/">花花酱 LeetCode 504. Base 7</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><iframe width="500" height="375" src="https://www.youtube.com/embed/fX6fh9B62vE?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1>Problem</h1>
<p>Given an integer, return its base 7 string representation.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b> 100
<b>Output:</b> "202"
</pre>
<p><b>Example 2:</b></p>
<pre class="crayon:false"><b>Input:</b> -7
<b>Output:</b> "-10"
</pre>
<p><b>Note:</b> The input will be in range of [-1e7, 1e7].</p>
<h1><strong>Solution: Simulation</strong></h1>
<p>Time complexity: O(logn)</p>
<p>Space complexity: O(logn)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 4 ms
class Solution {
public:
  string convertToBase7(int num) {
    bool is_nagetive = num&lt;0;
    num = abs(num);
    string ans;
    do {
        ans += ('0' + (num % 7));
        num /= 7;
    } while (num &gt; 0);
    
    if (is_nagetive)
        ans += "-";
    
    reverse(begin(ans), end(ans));
    
    return ans;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-504-base-7/">花花酱 LeetCode 504. Base 7</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/simulation/leetcode-504-base-7/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 800. Simple RGB Color</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-simple-rgb-color/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-simple-rgb-color/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 18 Mar 2018 05:05:45 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hex]]></category>
		<category><![CDATA[rgb]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2183</guid>

					<description><![CDATA[<p>Problem In the following, every capital letter represents some hexadecimal digit from 0 to f. The red-green-blue color "#AABBCC" can be written as "#ABC" in shorthand.  For example, "#15c" is shorthand for the color "#1155cc". Now, say&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-simple-rgb-color/">花花酱 LeetCode 800. Simple RGB Color</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>In the following, every capital letter represents some hexadecimal digit from <code>0</code> to <code>f</code>.</p>
<p>The red-green-blue color <code>"#AABBCC"</code> can be written as <code>"#ABC"</code> in shorthand.  For example, <code>"#15c"</code> is shorthand for the color <code>"#1155cc"</code>.</p>
<p>Now, say the similarity between two colors <code>"#ABCDEF"</code> and <code>"#UVWXYZ"</code> is <code>-(AB - UV)^2 - (CD - WX)^2 - (EF - YZ)^2</code>.</p>
<p>Given the color <code>"#ABCDEF"</code>, return a 7 character color that is most similar to <code>#ABCDEF</code>, and has a shorthand (that is, it can be represented as some <code>"#XYZ"</code></p>
<pre class="crayon:false "><strong>Example 1:</strong>
<strong>Input:</strong> color = "#09f166"
<strong>Output:</strong> "#11ee66"
<strong>Explanation: </strong> 
The similarity is -(0x09 - 0x11)^2 -(0xf1 - 0xee)^2 - (0x66 - 0x66)^2 = -64 -9 -0 = -73.
This is the highest among any shorthand color.
</pre>
<h2><strong>Note:</strong></h2>
<ul>
<li><code>color</code> is a string of length <code>7</code>.</li>
<li><code>color</code> is a valid RGB color: for <code>i &gt; 0</code>, <code>color[i]</code> is a hexadecimal digit from <code>0</code> to <code>f</code></li>
<li>Any answer which has the same (highest) similarity as the best answer will be accepted.</li>
<li>All inputs and outputs should use lowercase letters, and the output is 7 characters.</li>
</ul>
<h1><strong>Solution: Brute Force</strong></h1>
<p>R, G, B are independent, find the closest color for each channel separately.</p>
<p>Time complexity: O(3 * 16)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 7 ms
class Solution {
public:
  string similarRGB(string color) {
    const string hex{"0123456789abcdef"};
    vector&lt;int&gt; rgb(3, 0);
    for (int i = 0; i &lt; 3; ++i)
      rgb[i] = hex.find(color[2 * i + 1]) * 16 + hex.find(color[2 * i + 2]);
    
    string ans(7, '#');    
    for (int i = 0; i &lt; 3; ++i) {
      int best = INT_MAX;
      for (int j = 0; j &lt; 16; ++j) {
        int diff = abs(j * 16 + j - rgb[i]);
        if (diff &gt;= best) continue;
        best = diff;
        ans[2 * i + 1] = ans[2 * i + 2] = hex[j];
      }
    }
    return ans;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-simple-rgb-color/">花花酱 LeetCode 800. Simple RGB Color</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/string/leetcode-simple-rgb-color/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 297. Serialize and Deserialize Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-297-serialize-and-deserialize-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-297-serialize-and-deserialize-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 18 Sep 2017 02:55:45 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[serialization]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=316</guid>

					<description><![CDATA[<p>Problem: Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-297-serialize-and-deserialize-binary-tree/">花花酱 LeetCode 297. Serialize and Deserialize Binary Tree</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><iframe width="500" height="375" src="https://www.youtube.com/embed/JL4OjKV_pGE?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p>
<p>Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.</p>
<p>For example, you may serialize the following tree</p><pre class="crayon-plain-tag">1
   / \
  2   3
     / \
    4   5</pre><p>as <code>"[1,2,3,null,null,4,5]"</code>, just the same as <a href="https://leetcode.com/faq/#binary-tree">how LeetCode OJ serializes a binary tree</a>. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p>
<p><b>Note:</b> Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.</p>
<p><a href="https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/">https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/</a></p>
<p><strong>Idea:</strong></p>
<p>Recursion</p>
<p>Time Complexity O(n)</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-1.png"><img class="alignnone size-full wp-image-321" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-2.png"><img class="alignnone size-full wp-image-320" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-2-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<h1><strong>Solution 1: ASCII</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 39 ms
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        ostringstream out;
        serialize(root, out);
        return out.str();
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream in(data);
        return deserialize(in);
    }
private:
    void serialize(TreeNode* root, ostringstream&amp; out) {
        if (!root) {
            out &lt;&lt; "# ";
            return;
        }        
        out &lt;&lt; root-&gt;val &lt;&lt; " ";
        serialize(root-&gt;left, out);
        serialize(root-&gt;right, out);
    }
    
    TreeNode* deserialize(istringstream&amp; in) {
        string val;
        in &gt;&gt; val;
        if (val == "#") return nullptr;        
        TreeNode* root = new TreeNode(stoi(val));        
        root-&gt;left = deserialize(in);
        root-&gt;right = deserialize(in);        
        return root;
    }
};</pre><p></div></div></p>
<h1><strong>Solution 2: Binary</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 23 ms (beat 98.07%)
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        ostringstream out;
        serialize(root, out);
        return out.str();
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream in(data);
        return deserialize(in);
    }
private:
    enum STATUS {
        ROOT_NULL = 0x0,
        ROOT = 0x1,
        LEFT = 0x2,
        RIGHT = 0x4
    };
    
    void serialize(TreeNode* root, ostringstream&amp; out) {
        char status = 0;
        if (root) status |= ROOT;
        if (root &amp;&amp; root-&gt;left) status |= LEFT;
        if (root &amp;&amp; root-&gt;right) status |= RIGHT;
        out.write(&amp;status, sizeof(char));        
        if (!root) return;
        out.write(reinterpret_cast&lt;char*&gt;(&amp;(root-&gt;val)), sizeof(root-&gt;val));
        if (root-&gt;left) serialize(root-&gt;left, out);
        if (root-&gt;right) serialize(root-&gt;right, out);
    }
    
    TreeNode* deserialize(istringstream&amp; in) {
        char status;
        in.read(&amp;status, sizeof(char));
        if (!status &amp; ROOT) return nullptr;
        auto root = new TreeNode(0);
        in.read(reinterpret_cast&lt;char*&gt;(&amp;root-&gt;val), sizeof(root-&gt;val));        
        root-&gt;left = (status &amp; LEFT) ? deserialize(in) : nullptr;
        root-&gt;right = (status &amp; RIGHT) ? deserialize(in) : nullptr;
        return root;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));</pre><p></div><h2 class="tabtitle">C++ (string)</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 23 ms (&lt;98.13%)
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string s;
        serialize(root, s);
        return s;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) { 
        int pos = 0;
        return deserialize(data, pos);
    }
private:
    enum STATUS {
        ROOT_NULL = 0x0,
        ROOT = 0x1,
        LEFT = 0x2,
        RIGHT = 0x4
    };
    
    void serialize(TreeNode* root, string&amp; s) {
        char status = ROOT_NULL;
        if (root) status |= ROOT;
        if (root &amp;&amp; root-&gt;left) status |= LEFT;
        if (root &amp;&amp; root-&gt;right) status |= RIGHT;
        s.push_back(status);
        if (!root) return;
        s.append(reinterpret_cast&lt;char*&gt;(&amp;root-&gt;val), sizeof(root-&gt;val));
        if (root-&gt;left) serialize(root-&gt;left, s);
        if (root-&gt;right) serialize(root-&gt;right, s);
    }
    
    TreeNode* deserialize(const string&amp; s, int&amp; pos) {
        char status = s[pos++];
        if (!status) return nullptr;
        TreeNode* root = new TreeNode(0);
        memcpy(&amp;root-&gt;val, s.data() + pos, sizeof(root-&gt;val));
        pos += sizeof(root-&gt;val);  
        root-&gt;left = (status &amp; LEFT) ? deserialize(s, pos) : nullptr;
        root-&gt;right = (status &amp; RIGHT) ? deserialize(s, pos) : nullptr;
        return root;
    }
};</pre><p></div></div></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-449-serialize-and-deserialize-bst/">LeetCode 449. Serialize and Deserialize BST</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-297-serialize-and-deserialize-binary-tree/">花花酱 LeetCode 297. Serialize and Deserialize Binary Tree</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/tree/leetcode-297-serialize-and-deserialize-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
