1. 程式人生 > >Leetcode——338. 比特位計數

Leetcode——338. 比特位計數

ntb 數字 規劃 pro 需要 歸納 res amp tco

題目描述:題目鏈接

對於求解一個十進制數轉化為二進制時裏面1的個數,可以先看一下概況:

十進制數        二進制數        1的個數

  1            1           1

  2            10           1

  3            11           2

  4            100          1

  5            101           2

  6            110           2

  7            111           3

看上面的一系列數字的二進制中1的個數:

對於一個偶數 n ;其二進制組成最低位為0,所以其1的位數就是除了最低位之外前面那一部分中1的位數,即是i/21的位數。

對於一個奇數n,其末位的數一定是1,那麽對於n-1,一定是個偶數,並且只需要將n-1的末位0改成1就可以變成 n,因為 a[n] = a[n - 1] +1;

則可以得出上面兩個遞推關系式。

按照動態規劃的思路:

1:問題歸納:用數組a[ i ] 表示 i 的二進制中1的個數。

2:遞推關系式    a[n] = a[n/2]       n為偶數

          a[n] = a[n-1] +1       n為奇數

3:初始化:a[0] = 0

下面給出代碼:

class
Solution { public int[] countBits(int num) { int[] res = new int[num+1]; res[0] = 0; //先將所有的num轉化為偶數處理,因為沒有都是處理兩個數 int n = num%2 !=0 ? num-1:num; for(int i = 1; i <= n;i++){ res[i] = res[i-1]+1; i++; res[i] = res[i/2]; }
//最後有個奇數沒有處理 if(num % 2 != 0){ res[num] = res[n] + 1; } return res; } }

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

方法2:

對於一個數n,求解其二進制中1的個數可以利用位運算。

給出遞推關系式:a[i] = a[i&i-1]+1; 這個關系式可以有上面的實例歸納出來。

class Solution {
    public int[] countBits(int num) {
        int[] a = new int[num+1];
        for(int i =1;i <= num;i++){
            a[i] = a[i&i-1]+1;
        }
        return a;
    }
}

Leetcode——338. 比特位計數