位運算-leetcode_338

通過位運算計算出當前位的1的個數,原理利用Brian Kernighan 算法 令 x=x & (x−1) ,


/**
<p>給你一個整數 <code>n</code> ,對於&nbsp;<code>0 &lt;= i &lt;= n</code> 中的每個 <code>i</code> ,計算其二進制表示中 <strong><code>1</code> 的個數</strong> ,返回一個長度爲 <code>n + 1</code> 的數組 <code>ans</code> 作爲答案。</p>

<p>&nbsp;</p>

<div class="original__bRMd">
<div>
<p><strong>示例 1:</strong></p>

<pre>
<strong>輸入:</strong>n = 2
<strong>輸出:</strong>[0,1,1]
<strong>解釋:</strong>
0 --&gt; 0
1 --&gt; 1
2 --&gt; 10
</pre>

<p><strong>示例 2:</strong></p>

<pre>
<strong>輸入:</strong>n = 5
<strong>輸出:</strong>[0,1,1,2,1,2]
<strong>解釋:</strong>
0 --&gt; 0
1 --&gt; 1
2 --&gt; 10
3 --&gt; 11
4 --&gt; 100
5 --&gt; 101
</pre>

<p>&nbsp;</p>

<p><strong>提示:</strong></p>

<ul>
	<li><code>0 &lt;= n &lt;= 10<sup>5</sup></code></li>
</ul>

<p>&nbsp;</p>

<p><strong>進階:</strong></p>

<ul>
	<li>很容易就能實現時間複雜度爲 <code>O(n log n)</code> 的解決方案,你可以在線性時間複雜度 <code>O(n)</code> 內用一趟掃描解決此問題嗎?</li>
	<li>你能不使用任何內置函數解決此問題嗎?(如,C++ 中的&nbsp;<code>__builtin_popcount</code> )</li>
</ul>
</div>
</div>
<div><div>Related Topics</div><div><li>位運算</li><li>動態規劃</li></div></div><br><div><li>👍 1116</li><li>👎 0</li></div>
*/

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int[] countBits(int n) {
		int[] res = new int[n+1];
		for (int i = 0; i <= n; i++) {
			res[i]=countOnes(i);
		}
		return res;
    }

	int countOnes(int x){
		int countOnes = 0;
		while(x>0){
			x&=x-1;
			countOnes++;
		}
		return countOnes;
	}
}
//leetcode submit region end(Prohibit modification and deletion)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章