Skip to content
This repository has been archived by the owner on Feb 14, 2023. It is now read-only.

338. 比特位计数(中等) - https://leetcode-cn.com/problems/counting-bits/submissions/ #15

Open
tailgo opened this issue May 23, 2019 · 1 comment
Labels
阿狗 阿狗是帅哥呀

Comments

@tailgo
Copy link
Owner

tailgo commented May 23, 2019

先找一下规律,

0 -> 0 -> 0
1 -> 1 -> 1
2 -> 10 -> 1
3 -> 11 -> 2
4 -> 100 -> 1
5 -> 101 -> 2
6 -> 110 -> 2
7 -> 111 -> 3
......

可以得到规律就是 23 的二进制是在 01 的二进制最前面加 1,同理 47 是在 03 的最前面加 1 ,那么就可以以 0 和 1 的二进制个数为基础推算出每个数字的二进制数的 1 的个数。

执行用时 : 140 ms, 在Counting Bits的JavaScript提交中击败了96.63% 的用户
内存消耗 : 39.6 MB, 在Counting Bits的JavaScript提交中击败了57.58% 的用户

/**
 * @param {number} num
 * @return {number[]}
 */
var countBits = function(num) {
    if (num == 0) return [0];
    if (num == 1) return [0, 1];
    var result = [0, 1];
    
    var gap = 2;
    
    while (true) {
        for (var i = gap; i < 2 * gap; ++i) {
            result[i] = result[i - gap] + 1;
            
            if (i == num) {
                return result;
            }
        }
        gap *= 2;
    }
};
@tailgo
Copy link
Owner Author

tailgo commented May 23, 2019

根据一个公式 i & (i - 1),会把这个二进制数最右边的 1 去掉,也就是说 i 里面 1 的个数比 i & (i - 1) 多 1。

执行用时 : 144 ms, 在Counting Bits的JavaScript提交中击败了94.38% 的用户
内存消耗 : 39.9 MB, 在Counting Bits的JavaScript提交中击败了30.30% 的用户

/**
 * @param {number} num
 * @return {number[]}
 */
var countBits = function(num) {
    var result = [0];
    for (var i = 1; i <= num; ++i) {
        result[i] = result[i & (i - 1)] + 1;
    }
    return result; 
};

@tailgo tailgo added the 阿狗 阿狗是帅哥呀 label May 23, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
阿狗 阿狗是帅哥呀
Projects
None yet
Development

No branches or pull requests

1 participant