首页 > 其他 > 详细

LeetCode 338. Counting Bits

时间:2017-12-05 22:15:07      阅读:209      评论:0      收藏:0      [点我收藏+]

位运算

x&x-1 zero out the least significant 1

The first solution is to use the popCount method which could count the 1 bits for one specific number.

The time complexity O(kn). k is the number of 1 bits in the number.

class Solution {
    public int[] countBits(int num) {
        int[] ans = new int[num+1];
        for(int i = 0; i <= num; i++){
            ans[i] = popCount(i);
        }
        return ans;
    }
    public int popCount(int num){
        int count;
        for(count = 0; num != 0; count++){
            num &= num - 1;
        }
        return count;
    }
}

 The time complexity is O(n). 

For example 4(100) 3 (11) 2 (10) num(3) = num(2) + 1 num(4) = num(2).

floor(x/2) == x>>1. It discard the decimal points. If num % 2 == 0, then i & 1 == 0. If num % 2 == 1, then i & 1 == 1

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

 

LeetCode 338. Counting Bits

原文:http://www.cnblogs.com/ninalei/p/7989700.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!