[LeetCode] #338 位元位計數
阿新 • • 發佈:2021-09-17
[LeetCode] #338 位元位計數
給你一個整數 n
,對於0 <= i <= n
中的每個 i
,計算其二進位制表示中 1
的個數 ,返回一個長度為 n + 1
的陣列 ans
作為答案。
輸入:n = 2
輸出:[0,1,1]
解釋:
0 --> 0
1 --> 1
2 --> 10
使用API
class Solution { public int[] countBits(int n) { int[] res = new int[n+1]; for(int i = 0; i <= n; i++){ res[i]= Integer.bitCount(i); } return res; } }
n&(n-1) 其運算結果恰為把 n 的二進位制位中的最低位的 1 變為 0 之後的結果
class Solution { public int[] countBits(int n) { int[] bits = new int[n + 1]; for (int i = 0; i <= n; i++) { bits[i] = countOnes(i); } returnbits; } public int countOnes(int x) { int ones = 0; while (x > 0) { x &= (x - 1); ones++; } return ones; } }
動態規劃——最高有效位
class Solution { public int[] countBits(int n) { int[] bits = new int[n + 1]; int highBit = 0;for (int i = 1; i <= n; i++) { if ((i & (i - 1)) == 0) { highBit = i; } bits[i] = bits[i - highBit] + 1; } return bits; } }
動態規劃——最低有效位
class Solution { public int[] countBits(int n) { int[] bits = new int[n + 1]; for (int i = 1; i <= n; i++) { bits[i] = bits[i >> 1] + (i & 1); } return bits; } }
動態規劃——最低設定位
class Solution { public int[] countBits(int n) { int[] bits = new int[n + 1]; for (int i = 1; i <= n; i++) { bits[i] = bits[i & (i - 1)] + 1; } return bits; } }
知識點:無
總結:無