码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Counting Bits(338)

时间:2016-04-03 10:11:41      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

1. Description

  Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1‘s in their binary representation and return them as an array.

  Example:
  For num = 5 you should return [0,1,1,2,1,2].

2. Answer 

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

 

【LeetCode】Counting Bits(338)

标签:

原文地址:http://www.cnblogs.com/leesf456/p/5349083.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!