位元位計數
阿新 • • 發佈:2021-07-14
題目:
思路:
1Brian Kernighan演算法 x &= (x - 1) 每次可以從最右邊擦除一個二進數 1
2 動態規劃
(一)程式碼Brian Kernighan演算法
class Solution { public int[] countBits(int n) { //位運算 演算法 x &= (x - 1) 每次可以從最右邊擦除一個二進數 1 //Brian Kernighan演算法 int[] res = new int[n+1]; for(int i = 1 ; i <= n ; i++){ res[i]= getRes(i); } return res; } public int getRes(int i){ int res = 0; while(i > 0){ i &= (i - 1); res++; } return res; } }
(二)程式碼 動態規劃 -最低有效位 不太懂這個
class Solution { public int[] countBits(int n) {//動態規劃 int[] dp = new int[n+1]; for(int i = 1 ; i <= n ; i++){ dp[i] = dp[i >> 1] + (i & 1); } return dp; } }
。。。。。