【LeetCode】338. 比特位計數:位運算相關的知識

在這裏插入圖片描述

我的解題思路有兩種。第一種是利用Integer類的static int bitCount(int i) 函數。第二種是利用轉檯轉移方程:P(x)=P(x/2)+(xmod2)

class Solution {
    // public int[] countBits(int num) {
    //     int[] res = new int[num + 1];
    //     for (int i = 0; i < num + 1; i++) {
    //         res[i] = Integer.bitCount(i);
    //     }
    //     return res;
    // }
    public int[] countBits(int num) {
        int[] res = new int[num + 1];
        res[0] = 0;
        for (int i = 1; i < num + 1; i++) {
            res[i] = res[i >> 1] + (i & 1);
        }
        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章