通過位運算計算出當前位的1的個數,原理利用Brian Kernighan 算法 令 x=x & (x−1) ,
/**
<p>給你一個整數 <code>n</code> ,對於 <code>0 <= i <= n</code> 中的每個 <code>i</code> ,計算其二進制表示中 <strong><code>1</code> 的個數</strong> ,返回一個長度爲 <code>n + 1</code> 的數組 <code>ans</code> 作爲答案。</p>
<p> </p>
<div class="original__bRMd">
<div>
<p><strong>示例 1:</strong></p>
<pre>
<strong>輸入:</strong>n = 2
<strong>輸出:</strong>[0,1,1]
<strong>解釋:</strong>
0 --> 0
1 --> 1
2 --> 10
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>輸入:</strong>n = 5
<strong>輸出:</strong>[0,1,1,2,1,2]
<strong>解釋:</strong>
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 log n)</code> 的解決方案,你可以在線性時間複雜度 <code>O(n)</code> 內用一趟掃描解決此問題嗎?</li>
<li>你能不使用任何內置函數解決此問題嗎?(如,C++ 中的 <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)