mirror of
				https://gitee.com/coder-xiaomo/leetcode-problemset
				synced 2025-11-04 19:53:12 +08:00 
			
		
		
		
	
		
			
				
	
	
		
			51 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			HTML
		
	
	
	
	
	
			
		
		
	
	
			51 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			HTML
		
	
	
	
	
	
<p>给定一个非负整数 <code>n</code><b> </b>,请计算 <code>0</code> 到 <code>n</code> 之间的每个数字的二进制表示中 1 的个数,并输出一个数组。</p>
 | 
						||
 | 
						||
<p> </p>
 | 
						||
 | 
						||
<p><strong>示例 1:</strong></p>
 | 
						||
 | 
						||
<pre>
 | 
						||
<strong>输入: </strong>n =<strong> </strong>2
 | 
						||
<strong>输出: </strong>[0,1,1]
 | 
						||
<strong>解释: 
 | 
						||
</strong>0 --> 0
 | 
						||
1 --> 1
 | 
						||
2 --> 10
 | 
						||
</pre>
 | 
						||
 | 
						||
<p><strong>示例 2:</strong></p>
 | 
						||
 | 
						||
<pre>
 | 
						||
<strong>输入: </strong>n =<strong> </strong>5
 | 
						||
<strong>输出: </strong><code>[0,1,1,2,1,2]
 | 
						||
</code><span style="white-space: pre-wrap;"><strong>解释:</strong>
 | 
						||
</span>0 --> 0
 | 
						||
1 --> 1
 | 
						||
2 --> 10
 | 
						||
3 --> 11
 | 
						||
4 --> 100
 | 
						||
5 --> 101
 | 
						||
</pre>
 | 
						||
 | 
						||
<p> </p>
 | 
						||
 | 
						||
<p><strong>说明 :</strong></p>
 | 
						||
 | 
						||
<ul>
 | 
						||
	<li><code>0 <= n <= 10<sup>5</sup></code></li>
 | 
						||
</ul>
 | 
						||
 | 
						||
<p> </p>
 | 
						||
 | 
						||
<p><strong>进阶:</strong></p>
 | 
						||
 | 
						||
<ul>
 | 
						||
	<li>给出时间复杂度为 <code>O(n*sizeof(integer))</code><strong> </strong>的解答非常容易。但你可以在线性时间 <code>O(n)</code><strong> </strong>内用一趟扫描做到吗?</li>
 | 
						||
	<li>要求算法的空间复杂度为 <code>O(n)</code> 。</li>
 | 
						||
	<li>你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 <code>__builtin_popcount</code><strong> </strong>)来执行此操作。</li>
 | 
						||
</ul>
 | 
						||
 | 
						||
<p> </p>
 | 
						||
 | 
						||
<p><meta charset="UTF-8" />注意:本题与主站 338 题相同:<a href="https://leetcode-cn.com/problems/counting-bits/">https://leetcode-cn.com/problems/counting-bits/</a></p>
 |