Class Solution

java.lang.Object
g0301_0400.s0338_counting_bits.Solution

public class Solution extends Object
338 - Counting Bits.<p>Easy</p> <p>Given an integer <code>n</code>, return <em>an array</em> <code>ans</code> <em>of length</em> <code>n + 1</code> <em>such that for each</em> <code>i</code> (<code>0 <= i <= n</code>)<em>,</em> <code>ans[i]</code> <em>is the <strong>number of</strong></em> <code>1</code><em><strong>&rsquo;s</strong> in the binary representation of</em> <code>i</code>.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> n = 2</p> <p><strong>Output:</strong> [0,1,1]</p> <p><strong>Explanation:</strong></p> <pre><code> 0 --> 0 1 --> 1 2 --> 10 </code></pre> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> n = 5</p> <p><strong>Output:</strong> [0,1,1,2,1,2]</p> <p><strong>Explanation:</strong></p> <pre><code> 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 </code></pre> <p><strong>Constraints:</strong></p> <ul> <li><code>0 <= n <= 10<sup>5</sup></code></li> </ul> <p><strong>Follow up:</strong></p> <ul> <li>It is very easy to come up with a solution with a runtime of <code>O(n log n)</code>. Can you do it in linear time <code>O(n)</code> and possibly in a single pass?</li> <li>Can you do it without using any built-in function (i.e., like <code>__builtin_popcount</code> in C++)?</li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • countBits

      public int[] countBits(int num)