<?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>binary Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/binary/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/binary/</link>
	<description></description>
	<lastBuildDate>Fri, 31 Dec 2021 23:40:06 +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>binary Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/binary/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1980. Find Unique Binary String</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-1980-find-unique-binary-string/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-1980-find-unique-binary-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 31 Dec 2021 23:38:17 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9359</guid>

					<description><![CDATA[<p>Given an array of strings&#160;nums&#160;containing&#160;n&#160;unique&#160;binary strings each of length&#160;n, return&#160;a binary string of length&#160;n&#160;that&#160;does not appear&#160;in&#160;nums. If there are multiple answers, you may return&#160;any&#160;of them.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1980-find-unique-binary-string/">花花酱 LeetCode 1980. Find Unique Binary String</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 an array of strings&nbsp;<code>nums</code>&nbsp;containing&nbsp;<code>n</code>&nbsp;<strong>unique</strong>&nbsp;binary strings each of length&nbsp;<code>n</code>, return&nbsp;<em>a binary string of length&nbsp;</em><code>n</code><em>&nbsp;that&nbsp;<strong>does not appear</strong>&nbsp;in&nbsp;</em><code>nums</code><em>. If there are multiple answers, you may return&nbsp;<strong>any</strong>&nbsp;of them</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = ["01","10"]
<strong>Output:</strong> "11"
<strong>Explanation:</strong> "11" does not appear in nums. "00" would also be correct.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = ["00","01"]
<strong>Output:</strong> "11"
<strong>Explanation:</strong> "11" does not appear in nums. "10" would also be correct.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = ["111","011","001"]
<strong>Output:</strong> "101"
<strong>Explanation:</strong> "101" does not appear in nums. "000", "010", "100", and "110" would also be correct.
</pre>



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



<ul><li><code>n == nums.length</code></li><li><code>1 &lt;= n &lt;= 16</code></li><li><code>nums[i].length == n</code></li><li><code>nums[i]&nbsp;</code>is either&nbsp;<code>'0'</code>&nbsp;or&nbsp;<code>'1'</code>.</li><li>All the strings of&nbsp;<code>nums</code>&nbsp;are&nbsp;<strong>unique</strong>.</li></ul>



<h2><strong>Solution 1: Hashtable</strong></h2>



<p>We can use bitset to convert between integer and binary string.</p>



<p>Time complexity: O(n<sup>2</sup>)<br>Space complexity: <meta charset="utf-8">O(n<sup>2</sup>)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string findDifferentBinaryString(vector&lt;string&gt;&amp; nums) {
    const int n = nums.size();
    unordered_set&lt;int&gt; seen(1 &lt;&lt; n);
    for (const string&amp; num : nums)
      seen.insert(bitset&lt;16&gt;(num).to_ulong());
    for (int i = 0; i &lt; 1 &lt;&lt; n; ++i)
      if (!seen.count(i)) return bitset&lt;16&gt;(i).to_string().substr(16 - n);
    return &quot;&quot;;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: One bit a time</strong></h2>



<p>Let ans[i] = &#8216;1&#8217; &#8211; nums[i][i], s.t. ans is at least one bit different from any strings.</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:
  string findDifferentBinaryString(vector&lt;string&gt;&amp; nums) {    
    const int n = nums.size();
    string ans(n, '0');
    for (int i = 0; i &lt; n; ++i)
      ans[i] = '1' - nums[i][i] + '0';
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1980-find-unique-binary-string/">花花酱 LeetCode 1980. Find Unique Binary String</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/bit/leetcode-1980-find-unique-binary-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 29. Divide Two Integers</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-29-divide-two-integers/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-29-divide-two-integers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 26 Nov 2021 21:48:08 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8785</guid>

					<description><![CDATA[<p>Given two integers&#160;dividend&#160;and&#160;divisor, divide two integers&#160;without&#160;using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-29-divide-two-integers/">花花酱 LeetCode 29. Divide Two Integers</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 two integers&nbsp;<code>dividend</code>&nbsp;and&nbsp;<code>divisor</code>, divide two integers&nbsp;<strong>without</strong>&nbsp;using multiplication, division, and mod operator.</p>



<p>The integer division should truncate toward zero, which means losing its fractional part. For example,&nbsp;<code>8.345</code>&nbsp;would be truncated to&nbsp;<code>8</code>, and&nbsp;<code>-2.7335</code>&nbsp;would be truncated to&nbsp;<code>-2</code>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>quotient</strong>&nbsp;after dividing&nbsp;</em><code>dividend</code><em>&nbsp;by&nbsp;</em><code>divisor</code>.</p>



<p><strong>Note:&nbsp;</strong>Assume we are dealing with an environment that could only store integers within the&nbsp;<strong>32-bit</strong>&nbsp;signed integer range:&nbsp;<code>[−2<sup>31</sup>, 2<sup>31</sup>&nbsp;− 1]</code>. For this problem, if the quotient is&nbsp;<strong>strictly greater than</strong>&nbsp;<code>2<sup>31</sup>&nbsp;- 1</code>, then return&nbsp;<code>2<sup>31</sup>&nbsp;- 1</code>, and if the quotient is&nbsp;<strong>strictly less than</strong>&nbsp;<code>-2<sup>31</sup></code>, then return&nbsp;<code>-2<sup>31</sup></code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> dividend = 10, divisor = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> 10/3 = 3.33333.. which is truncated to 3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> dividend = 7, divisor = -3
<strong>Output:</strong> -2
<strong>Explanation:</strong> 7/-3 = -2.33333.. which is truncated to -2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> dividend = 0, divisor = 1
<strong>Output:</strong> 0
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> dividend = 1, divisor = 1
<strong>Output:</strong> 1
</pre>



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



<ul><li><code>-2<sup>31</sup>&nbsp;&lt;= dividend, divisor &lt;= 2<sup>31</sup>&nbsp;- 1</code></li><li><code>divisor != 0</code></li></ul>



<h2><strong>Solution: Binary / Bit Operation</strong></h2>



<p>The answer can be represented in binary format.</p>



<p>a / b = c<br>a >= b *  Σ(d<sub>i</sub>*2<sup>i</sup>)<br>c = Σ(d<sub>i</sub>*2<sup>i</sup>)</p>



<p>e.g. 1: 10 / 3<br>=> 10 >= 3*(2<sup>1</sup> + 2<sup>0</sup>) = 3 * (2 + 1) = 9<br>ans = 2<sup>1</sup> + 2<sup>0</sup> = 3<br><br>e.g. 2: 100 / 7<br>=> 100 >= 7*(2<sup>3</sup> + 2<sup>2</sup>+2<sup>1</sup>) = 7 * (8 + 4 + 2) = 7 * 14 = 98<br>ans = 2<sup>3</sup>+2<sup>2</sup>+2<sup>1</sup>=8+4+2=14</p>



<p>Time complexity: O(32)<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 divide(int A, int B) {
    if (B == INT_MIN)
      return A == INT_MIN ? 1 : 0;
    if (A == INT_MIN) {
      if (B == -1) return INT_MAX;
      return B &gt; 0 ? divide(A + B, B) - 1 : divide(A - B, B) + 1;
    }    
    int a = abs(A);
    int b = abs(B);
    int ans = 0;
    for (int x = 31; x &gt;= 0; --x)
      if (a &gt;&gt; x &gt;= b)
        ans += 1 &lt;&lt; x, a -= b &lt;&lt; x;
    return (A &gt; 0) == (B &gt; 0) ? ans : -ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-29-divide-two-integers/">花花酱 LeetCode 29. Divide Two Integers</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/bit/leetcode-29-divide-two-integers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1702. Maximum Binary String After Change</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1702-maximum-binary-string-after-change/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1702-maximum-binary-string-after-change/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Dec 2020 02:47:25 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7849</guid>

					<description><![CDATA[<p>You are given a binary string&#160;binary&#160;consisting of only&#160;0&#8216;s or&#160;1&#8216;s. You can apply each of the following operations any number of times: Operation 1: If the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1702-maximum-binary-string-after-change/">花花酱 LeetCode 1702. Maximum Binary String After Change</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 given a binary string&nbsp;<code>binary</code>&nbsp;consisting of only&nbsp;<code>0</code>&#8216;s or&nbsp;<code>1</code>&#8216;s. You can apply each of the following operations any number of times:</p>



<ul><li>Operation 1: If the number contains the substring&nbsp;<code>"00"</code>, you can replace it with&nbsp;<code>"10"</code>.<ul><li>For example,&nbsp;<code>"00010" -&gt; "10010</code>&#8220;</li></ul></li><li>Operation 2: If the number contains the substring&nbsp;<code>"10"</code>, you can replace it with&nbsp;<code>"01"</code>.<ul><li>For example,&nbsp;<code>"00010" -&gt; "00001"</code></li></ul></li></ul>



<p><em>Return the&nbsp;<strong>maximum binary string</strong>&nbsp;you can obtain after any number of operations. Binary string&nbsp;<code>x</code>&nbsp;is greater than binary string&nbsp;<code>y</code>&nbsp;if&nbsp;<code>x</code>&#8216;s decimal representation is greater than&nbsp;<code>y</code>&#8216;s decimal representation.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> binary = "000110"
<strong>Output:</strong> "111011"
<strong>Explanation:</strong> A valid transformation sequence can be:
"000110" -&gt; "000101" 
"000101" -&gt; "100101" 
"100101" -&gt; "110101" 
"110101" -&gt; "110011" 
"110011" -&gt; "111011"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> binary = "01"
<strong>Output:</strong> "01"
<strong>Explanation:</strong>&nbsp;"01" cannot be transformed any further.
</pre>



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



<ul><li><code>1 &lt;= binary.length &lt;= 10<sup>5</sup></code></li><li><code>binary</code>&nbsp;consist of&nbsp;<code>'0'</code>&nbsp;and&nbsp;<code>'1'</code>.</li></ul>



<h2><strong>Solution: Greedy + Counting</strong></h2>



<p>Leading 1s are good, no need to change them.<br>For the rest of the string<br>1. Apply operation 2 to make the string into 3 parts, leading 1s, middle 0s and tailing 1s.<br>e.g. 110<strong>1010</strong>1 =&gt; 11001<strong>10</strong>1 =&gt; 1100<strong>10</strong>11 =&gt; 11000111<br>2. Apply operation 1 to make flip zeros to ones except the last one.<br>e.g. 11<strong>00</strong>0111 =&gt; 111<strong>00</strong>111 =&gt; 11110111<br><br>There will be only one zero (if the input string is not all 1s) is the final largest string, the position of the zero is leading 1s + zeros &#8211; 1.</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">class Solution {
public:
  string maximumBinaryString(string s) {
    const int n = s.length();
    int l = 0;
    int z = 0;
    for (char&amp; c : s) {
      if (c == '0') {
        ++z;
      } else if (z == 0) { // leading 1s      
        ++l;
      }
      c = '1';
    }
    if (l != n) s[l + z - 1] = '0';
    return s;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1702-maximum-binary-string-after-change/">花花酱 LeetCode 1702. Maximum Binary String After Change</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/greedy/leetcode-1702-maximum-binary-string-after-change/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1558. Minimum Numbers of Function Calls to Make Target Array</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-1558-minimum-numbers-of-function-calls-to-make-target-array/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-1558-minimum-numbers-of-function-calls-to-make-target-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 22 Aug 2020 18:59:41 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[highest bit]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7278</guid>

					<description><![CDATA[<p>Your task is to form&#160;an integer array&#160;nums&#160;from an initial array of zeros&#160;arr&#160;that is the&#160;same size&#160;as&#160;nums. Return the minimum number of&#160;function calls to make&#160;nums&#160;from&#160;arr. The answer&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1558-minimum-numbers-of-function-calls-to-make-target-array/">花花酱 LeetCode 1558. Minimum Numbers of Function Calls to Make Target Array</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-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1558. Minimum Numbers of Function Calls to Make Target Array - 刷题找工作 EP351" width="500" height="281" src="https://www.youtube.com/embed/YQlNemdLtCc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/07/10/sample_2_1887.png" alt=""/></figure>



<p>Your task is to form&nbsp;an integer array&nbsp;<code>nums</code>&nbsp;from an initial array of zeros&nbsp;<code>arr</code>&nbsp;that is the&nbsp;same size&nbsp;as&nbsp;<code>nums</code>.</p>



<p>Return the minimum number of&nbsp;function calls to make&nbsp;<code>nums</code>&nbsp;from&nbsp;<code>arr</code>.</p>



<p>The answer is guaranteed to fit in a 32-bit signed integer.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,5]
<strong>Output:</strong> 5
<strong>Explanation:</strong> Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).
Double all the elements: [0, 1] -&gt; [0, 2] -&gt; [0, 4] (2 operations).
Increment by 1 (both elements)  [0, 4] -&gt; [1, 4] -&gt; <strong>[1, 5]</strong> (2 operations).
Total of operations: 1 + 2 + 2 = 5.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Increment by 1 (both elements) [0, 0] -&gt; [0, 1] -&gt; [1, 1] (2 operations).
Double all the elements: [1, 1] -&gt; <strong>[2, 2]</strong> (1 operation).
Total of operations: 2 + 1 = 3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [4,2,5]
<strong>Output:</strong> 6
<strong>Explanation:</strong> (initial)[0,0,0] -&gt; [1,0,0] -&gt; [1,0,1] -&gt; [2,0,2] -&gt; [2,1,2] -&gt; [4,2,4] -&gt; <strong>[4,2,5]</strong>(nums).
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,2,2,4]
<strong>Output:</strong> 7
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,4,8,16]
<strong>Output:</strong> 8
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 10^5</code></li><li><code>0 &lt;= nums[i] &lt;= 10^9</code></li></ul>



<h2><strong>Solution: count 1s</strong></h2>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/08/1558-ep351.png" alt="" class="wp-image-7288" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/08/1558-ep351.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/08/1558-ep351-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/08/1558-ep351-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/08/1558-ep351-2.png" alt="" class="wp-image-7287" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/08/1558-ep351-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/08/1558-ep351-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/08/1558-ep351-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>For 5 (101b), we can add 1s for 5 times which of cause isn&#8217;t the best way to generate 5, the optimal way is to [+1, *2, +1]. We have to add 1 for each 1 in the binary format. e.g. 11 (1011), we need 3x &#8220;+1&#8221; op, and 4 &#8220;*2&#8221; op.  Fortunately, the &#8220;*2&#8221; can be shared/delayed,  thus we just need to find the largest number.<br>e.g. [2,4,8,16]<br>[0, 0, 0, 0] -&gt; [0, 0, 0, 1] -&gt; [0, 0, 0, 2]<br>[0, 0, 0, 2] -&gt; [0, 0, 1, 2] -&gt; [0, 0, 2, 4]<br>[0, 0, 2, 4] -&gt; [0, 1, 2, 4] -&gt; [0, 2, 4, 8]<br>[0, 2, 4, 8] -&gt; [1, 2, 4, 8] -&gt; [2, 4, 8, 16]<br>ans = sum{count_1(arr_i)} + high_bit(max(arr_i))</p>



<p>Time complexity: O(n*log(max(arr_i))<br>Space complexity: O(1)</p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  int minOperations(vector&lt;int&gt;&amp; nums) {
    int ans = 0;
    int high = 0;
    for (int x : nums) {
      high = max(high, 31 - __builtin_clz(x | 1));
      ans += std::bitset&lt;32&gt;(x).count();
    }
    return ans + high;
  }
};</pre>

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

<pre class="crayon-plain-tag">class Solution {
  public int minOperations(int[] nums) {
    int ans = 0;
    int high = 0;
    for (int x : nums) {
      int l = -1;
      while (x != 0) {        
        ans += x &amp; 1;
        x &gt;&gt;= 1; 
        ++l;
      }
      high = Math.max(high, l);
    }
    return ans + high;
  }
}</pre>

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

<pre class="crayon-plain-tag">class Solution:
  def minOperations(self, nums: List[int]) -&gt; int:
    return sum(bin(x).count('1') for x in nums) + len(bin(max(nums))) - 3</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1558-minimum-numbers-of-function-calls-to-make-target-array/">花花酱 LeetCode 1558. Minimum Numbers of Function Calls to Make Target Array</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/bit/leetcode-1558-minimum-numbers-of-function-calls-to-make-target-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1261. Find Elements in a Contaminated Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-1261-find-elements-in-a-contaminated-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-1261-find-elements-in-a-contaminated-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 27 Nov 2019 01:10:41 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5872</guid>

					<description><![CDATA[<p>Given a&#160;binary tree with the following rules: root.val == 0 If&#160;treeNode.val == x&#160;and&#160;treeNode.left != null, then&#160;treeNode.left.val == 2 * x + 1 If&#160;treeNode.val == x&#160;and&#160;treeNode.right&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1261-find-elements-in-a-contaminated-binary-tree/">花花酱 LeetCode 1261. Find Elements in a Contaminated 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>Given a&nbsp;binary tree with the following rules:</p>



<ol><li><code>root.val == 0</code></li><li>If&nbsp;<code>treeNode.val == x</code>&nbsp;and&nbsp;<code>treeNode.left != null</code>, then&nbsp;<code>treeNode.left.val == 2 * x + 1</code></li><li>If&nbsp;<code>treeNode.val == x</code>&nbsp;and&nbsp;<code>treeNode.right != null</code>, then&nbsp;<code>treeNode.right.val == 2 * x + 2</code></li></ol>



<p>Now the binary tree is contaminated, which means all&nbsp;<code>treeNode.val</code>&nbsp;have&nbsp;been changed to&nbsp;<code>-1</code>.</p>



<p>You need to first recover the binary tree and then implement the&nbsp;<code>FindElements</code>&nbsp;class:</p>



<ul><li><code>FindElements(TreeNode* root)</code>&nbsp;Initializes the object with a&nbsp;contamined binary tree, you need to recover it first.</li><li><code>bool find(int target)</code>&nbsp;Return if the&nbsp;<code>target</code>&nbsp;value exists in the recovered binary tree.</li></ul>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4-1.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input</strong>
["FindElements","find","find"]
[[[-1,null,-1]],[1],[2]]
<strong>Output</strong>
</pre>


<p>[null,false,true]</p>



<p><strong>Explanation</strong>
FindElements findElements = new FindElements([-1,null,-1]); 
findElements.find(1); // return False 
findElements.find(2); // return True </p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input</strong>
["FindElements","find","find","find"]
[[[-1,-1,-1,-1,-1]],[1],[3],[5]]
<strong>Output</strong>
</pre>


<p>[null,true,true,false]</p>



<p><strong>Explanation</strong>
FindElements findElements = new FindElements([-1,-1,-1,-1,-1]);
findElements.find(1); // return True
findElements.find(3); // return True
findElements.find(5); // return False</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/11/07/untitled-diagram-4-1-1.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input</strong>
["FindElements","find","find","find","find"]
[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]
<strong>Output</strong>
</pre>


<p>[null,true,false,false,true]</p>



<p><strong>Explanation</strong>
FindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);
findElements.find(2); // return True
findElements.find(3); // return False
findElements.find(4); // return False
findElements.find(5); // return True
</p>



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



<ul><li><code>TreeNode.val == -1</code></li><li>The height of the binary tree is less than or equal to&nbsp;<code>20</code></li><li>The total number of nodes is between&nbsp;<code>[1,&nbsp;10^4]</code></li><li>Total calls of&nbsp;<code>find()</code>&nbsp;is between&nbsp;<code>[1,&nbsp;10^4]</code></li><li><code>0 &lt;= target &lt;= 10^6</code></li></ul>



<h2><strong>Solutoin 1: Recursion and HashSet</strong></h2>



<p>Time complexity: Recover O(n), find O(1)<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 FindElements {
public:
  FindElements(TreeNode* root) {
    recover(root, 0);
  }

  bool find(int target) {
    return s_.count(target);
  }
private:
  unordered_set&lt;int&gt; s_;
  void recover(TreeNode* root, int val) {
    if (!root) return;
    root-&gt;val = val;
    s_.insert(val);
    recover(root-&gt;left, val * 2 + 1);
    recover(root-&gt;right, val * 2 + 2);
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Recursion and Binary format</strong></h2>



<p>The binary format of t = (target + 1) (from high bit to low bit, e.g. in reverse order) decides where to go at each node.<br>t % 2 == 1, go right, otherwise go left<br>t = t / 2 or t >>= 1</p>



<pre class="crayon-plain-tag">e.g. target = 13, t = 13 + 1 = 14
t = 14, t % 1 = 0, t / 2 = 7, left
t = 7, t % 1 = 1, t / 2 = 3, right
t = 3, t % 1 = 1, t / 2 = 1, right
13 =&gt; right, right, left 
0
 \
  2
    \
     6
   /
13</pre>



<p>Time complexity: Recover O(n), find O(log|target|)<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 FindElements {
public:
  FindElements(TreeNode* root): root_(root) {
    recover(root, 0);
  }

  bool find(int target) {    
    ++target;
    stack&lt;bool&gt; right;
    while (target != 1) {
      right.push(target &amp; 1);
      target &gt;&gt;= 1;
    }
    
    TreeNode* node = root_;
    while (!right.empty() &amp;&amp; node) {
      node = right.top() ? node-&gt;right : node-&gt;left;
      right.pop();
    }
    
    return node;
  }
private:
  TreeNode* root_;
  void recover(TreeNode* root, int val) {
    if (!root) return;
    root-&gt;val = val;    
    recover(root-&gt;left, val * 2 + 1);
    recover(root-&gt;right, val * 2 + 2);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1261-find-elements-in-a-contaminated-binary-tree/">花花酱 LeetCode 1261. Find Elements in a Contaminated 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-1261-find-elements-in-a-contaminated-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 78. Subsets</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-78-subsets/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-78-subsets/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 22 Dec 2018 17:58:12 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[combination]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[search]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4521</guid>

					<description><![CDATA[<p>Given a set of&#160;distinct&#160;integers,&#160;nums, return all possible subsets (the power set). Note:&#160;The solution set must not contain duplicate subsets. Example: Input: nums = [1,2,3]Output:[ [3],&#160;&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-78-subsets/">花花酱 LeetCode 78. Subsets</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 width="500" height="375" src="https://www.youtube.com/embed/CUzm-buvH_8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given a set of&nbsp;<strong>distinct</strong>&nbsp;integers,&nbsp;<em>nums</em>, return all possible subsets (the power set).</p>



<p><strong>Note:</strong>&nbsp;The solution set must not contain duplicate subsets.</p>



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



<pre class="wp-block-preformatted crayon:false"><strong>Input:</strong> nums = [1,2,3]<br><strong>Output:</strong>[  [3],&nbsp; [1],&nbsp; [2],&nbsp; [1,2,3],&nbsp; [1,3],&nbsp; [2,3],&nbsp; [1,2],&nbsp; []]</pre>



<h1><strong>Solution: Combination</strong></h1>



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



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/78-ep236.png" alt="" class="wp-image-4530" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/78-ep236.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/78-ep236-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/78-ep236-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<h2><strong>Implemention 1: DFS</strong></h2>



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

<pre class="crayon-plain-tag">// Author: Huahua, running time: 4 ms
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; subsets(vector&lt;int&gt;&amp; nums) {
    vector&lt;vector&lt;int&gt;&gt; ans;
    vector&lt;int&gt; cur;
    for (int i = 0; i &lt;= nums.size(); ++i)
      dfs(nums, i, 0, cur, ans);
    return ans;
  }
private:  
  void dfs(const vector&lt;int&gt;&amp; nums, int n, int s, 
           vector&lt;int&gt;&amp; cur, vector&lt;vector&lt;int&gt;&gt;&amp; ans) {
    if (n == cur.size()) {
      ans.push_back(cur);
      return;
    }
    for (int i = s; i &lt; nums.size(); ++i) {
      cur.push_back(nums[i]);
      dfs(nums, n, i + 1, cur, ans);
      cur.pop_back();
    }
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua, running time: 60 ms
class Solution:
  def subsets(self, nums):
    ans = []
    def dfs(n, s, cur):
      if n == len(cur):
        ans.append(cur.copy())
        return
      for i in range(s, len(nums)):
        cur.append(nums[i])
        dfs(n, i + 1, cur)
        cur.pop()
    for i in range(len(nums) + 1):
      dfs(i, 0, [])
    return ans</pre>
</div></div>



<h2><strong>Implementation 2: Binary</strong></h2>



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

<pre class="crayon-plain-tag">// Author: Huahua, running time: 4 ms
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; subsets(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    vector&lt;vector&lt;int&gt;&gt; ans;    
    for (int s = 0; s &lt; 1 &lt;&lt; n; ++s) {
      vector&lt;int&gt; cur;
      for (int i = 0; i &lt; n; ++i)
        if (s &amp; (1 &lt;&lt; i)) cur.push_back(nums[i]);
      ans.push_back(cur);
    }
    return ans;
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua, 40 ms
class Solution:
  def subsets(self, nums):
    n = len(nums)
    return [[nums[i] for i in range(n) if s &amp; 1 &lt;&lt; i &gt; 0] for s in range(1 &lt;&lt; n)]</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-78-subsets/">花花酱 LeetCode 78. Subsets</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/searching/leetcode-78-subsets/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 869. Reordered Power of 2</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-869-reordered-power-of-2/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-869-reordered-power-of-2/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Jul 2018 05:32:45 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3165</guid>

					<description><![CDATA[<p>Problem Starting with a positive integer N, we reorder the digits in any order (including the original order) such that the leading digit is not zero.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-869-reordered-power-of-2/">花花酱 LeetCode 869. Reordered Power of 2</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>Starting with a positive integer <code>N</code>, we reorder the digits in any order (including the original order) such that the leading digit is not zero.</p>
<p>Return <code>true</code> if and only if we can do this in a way such that the resulting number is a power of 2.</p>
<div>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">1</span>
<strong>Output: </strong><span id="example-output-1">true</span>
</pre>
<div>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-2-1">10</span>
<strong>Output: </strong><span id="example-output-2">false</span>
</pre>
<div>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-3-1">16</span>
<strong>Output: </strong><span id="example-output-3">true</span>
</pre>
<div>
<p><strong>Example 4:</strong></p>
<pre class="crayon:false "><strong>Input: </strong><span id="example-input-4-1">24</span>
<strong>Output: </strong><span id="example-output-4">false</span>
</pre>
<div>
<p><strong>Example 5:</strong></p><pre class="crayon-plain-tag">&lt;strong&gt;Input: &lt;/strong&gt;&lt;span id=&quot;example-input-5-1&quot;&gt;46&lt;/span&gt;
&lt;strong&gt;Output: &lt;/strong&gt;&lt;span id=&quot;example-output-5&quot;&gt;true&lt;/span&gt;</pre><p><strong>Note:</strong></p>
<ol>
<li><code>1 &lt;= N &lt;= 10^9</code></li>
</ol>
</div>
</div>
</div>
</div>
</div>
<h1><strong>Solution: HashTable</strong></h1>
<p>Compare the counter of digit string with that of all power of 2s.</p>
<p>e.g. 64 -&gt; {4: 1, 6: 1} == 46 {4:1, 6: 1}</p>
<p>Time complexity: O(1)</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool reorderedPowerOf2(int N) {    
    auto m = countMap(N);
    for (int i = 0; i &lt; 31; ++i)
      if (m == countMap(1 &lt;&lt; i)) return true;
    return false;
  }
private:
  map&lt;int, int&gt; countMap(int n) {
    map&lt;int, int&gt; m;
    while (n) {
      ++m[n % 10];
      n /= 10;
    }
    return m;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-869-reordered-power-of-2/">花花酱 LeetCode 869. Reordered Power of 2</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-869-reordered-power-of-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 868. Binary Gap</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-868-binary-gap/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-868-binary-gap/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Jul 2018 03:44:13 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[easy]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3144</guid>

					<description><![CDATA[<p>Problem Given a positive integer N, find and return the longest distance between two consecutive 1&#8217;s in the binary representation of N. If there aren&#8217;t two consecutive 1&#8217;s,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-868-binary-gap/">花花酱 LeetCode 868. Binary Gap</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>Problem</h1>
<p>Given a positive integer <code>N</code>, find and return the longest distance between two consecutive 1&#8217;s in the binary representation of <code>N</code>.</p>
<p>If there aren&#8217;t two consecutive 1&#8217;s, return <span style="font-family: monospace;">0</span>.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">22</span>
<strong>Output: </strong>2
<strong>Explanation: </strong>
22 in binary is 0b10110.
In the binary representation of 22, there are three ones, and two consecutive pairs of 1's.
The first consecutive pair of 1's have distance 2.
The second consecutive pair of 1's have distance 1.
The answer is the largest of these two distances, which is 2.
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-2-1">5</span>
<strong>Output: </strong><span id="example-output-2">2</span>
<strong>Explanation: </strong>
5 in binary is 0b101.
</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-3-1">6</span>
<strong>Output: </strong><span id="example-output-3">1</span>
<strong>Explanation: </strong>
6 in binary is 0b110.
</pre>
<p><strong>Example 4:</strong></p>
<pre class="crayon:false "><strong>Input: </strong><span id="example-input-4-1">8</span>
<strong>Output: </strong><span id="example-output-4">0</span>
<strong>Explanation: </strong>
8 in binary is 0b1000.
There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0.\
</pre>
<p><strong>Note:</strong></p>
<ul>
<li><code>1 &lt;= N &lt;= 10^9</code></li>
</ul>
<h1><strong>Solution: Bit</strong></h1>
<p>Time complexity: O(logN)</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 4 ms
class Solution {
public:
  int binaryGap(int N) {
    int l = -1;
    int ans = 0;
    for (int i = 0; i &lt; 31; ++i)
      if (N &amp; (1 &lt;&lt; i)) {
        if (l &gt;= 0)
          ans = max(ans, i - l);
        l = i;
      }
    return ans;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-868-binary-gap/">花花酱 LeetCode 868. Binary Gap</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/bit/leetcode-868-binary-gap/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>
		<item>
		<title>花花酱 LeetCode 669. Trim a Binary Search Tree</title>
		<link>https://zxi.mytechroad.com/blog/leetcode/leetcode-669-trim-a-binary-search-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/leetcode/leetcode-669-trim-a-binary-search-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 05 Sep 2017 01:13:36 +0000</pubDate>
				<category><![CDATA[Leetcode]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[binary search tree]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[memory leak]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[trim]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=90</guid>

					<description><![CDATA[<p>Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R &#62;= L).&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-669-trim-a-binary-search-tree/">花花酱 LeetCode 669. Trim a Binary Search 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/L_t2x3nH61k?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>Given a binary search tree and the lowest and highest boundaries as <code>L</code> and <code>R</code>, trim the tree so that all its elements lies in <code>[L, R]</code> (R &gt;= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input:
    1
   / \
  0   2

  L = 1
  R = 2

Output: 
    1
      \
       2</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input:
    3
   / \
  0   4
   \
    2
   /
  1

  L = 1
  R = 3

Output:
      3
     / 
   2   
  /
 1</pre><p>This problem can be solved with recursion</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/699-1-1.png"><img class="alignnone wp-image-100 size-full" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/699-1-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/699-1-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/699-1-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/699-1-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/699-1-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p>There 3 cases in total depends on the root value and L, R</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p>Solution:</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
    // No cleanup -&gt; memory leak 
    TreeNode* trimBST(TreeNode* root, int L, int R) {
        if(!root) return nullptr;
        // val not in range, return the left/right subtrees
        if(root-&gt;val &lt; L) return trimBST(root-&gt;right, L, R);
        if(root-&gt;val &gt; R) return trimBST(root-&gt;left, L, R);
        // val in [L, R], recusively trim left/right subtrees
        root-&gt;left = trimBST(root-&gt;left, L, R);
        root-&gt;right = trimBST(root-&gt;right, L, R);
        return root;
    }
};</pre><p>The previous solution has potential memory leak for languages without garbage collection.</p>
<p>Here&#8217;s the full program to delete trimmed nodes.</p><pre class="crayon-plain-tag">// Author: Huahua
#include &lt;iostream&gt;
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
 
class Solution {
public:
    
    // With cleanup -&gt; no memory leak
    TreeNode*&amp; trimBST(TreeNode*&amp; root, int L, int R) {
        if(!root) return root;
        
        if(root-&gt;val &lt; L) {            
            auto&amp; result = trimBST(root-&gt;right, L, R);
            deleteTree(root-&gt;left);
            delete root;
            root=nullptr;
            return result;
        } else if(root-&gt;val &gt; R) {
            auto&amp; result = trimBST(root-&gt;left, L, R);
            deleteTree(root-&gt;right);
            delete root;
            root=nullptr;
            return result;
        } else {
            // recusively trim left/right subtrees
            root-&gt;left = trimBST(root-&gt;left, L, R);
            root-&gt;right = trimBST(root-&gt;right, L, R);
            return root;
        }
    }
    
    void deleteTree(TreeNode* &amp;root) {
        if(!root) return;
        deleteTree(root-&gt;left);
        deleteTree(root-&gt;right);
        delete root;
        root=nullptr;
    }
};

void PrintTree(TreeNode* root) {
    if(!root) {
        cout&lt;&lt;"null ";
        return;
    };
    if(!root-&gt;left &amp;&amp; !root-&gt;right) {
        cout&lt;&lt;root-&gt;val&lt;&lt;" ";
    } else {
        cout&lt;&lt;root-&gt;val&lt;&lt;" ";
        PrintTree(root-&gt;left);
        PrintTree(root-&gt;right);
    }
}


int main()
{
    TreeNode* root=new TreeNode(2);
    root-&gt;left=new TreeNode(1);
    root-&gt;right=new TreeNode(3);
    PrintTree(root);
    std::cout&lt;&lt;std::endl;
    
    TreeNode* t = Solution().trimBST(root, 3, 4);
    PrintTree(t);
    std::cout&lt;&lt;std::endl;

    // Original root was deleted
    PrintTree(root);
    std::cout&lt;&lt;std::endl;
    
    return 0;
}</pre><p>Example output</p><pre class="crayon-plain-tag">2 1 3 
3 
null</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-669-trim-a-binary-search-tree/">花花酱 LeetCode 669. Trim a Binary Search 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/leetcode/leetcode-669-trim-a-binary-search-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
