TypechoJoeTheme

IT技术分享

统计

[LeetCode 338] Counting Bits [Java] [Runtime : 2MS]

2017-08-04
/
0 评论
/
599 阅读
/
正在检测是否收录...
08/04

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.

2. Runtime Distribution

3. Submission Details

4. Example

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

5. Code

public int[] countBits(int num)
{
    int[] res = new int[num + 1];
    for (int i = 1; i <= num; i++) {
        res[i] = res[i >> 1] + (i & 1);
    }
    return res;
}
public int[] countBits(int num)
{
    int[] results = new int[num + 1];
    for (int i = 0; i <= num; i++) {
        results[i] = bitCount(i);
    }
    return results;
}

private int bitCount(int number)
{
    int count = 0;
    while (number != 0) {
        count++;
        number = (number - 1) & number;
    }
    return count;
}

6.Test

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

    public static void main(String[] args)
    {
        LeetCode0038 leetcode = new LeetCode0038();
        int[] results = leetcode.countBits(5);
        for (int result : results) {
            System.out.println(result);
        }
    }
}
public class LeetCode0338 {
    public int[] countBits(int num)
    {
        int[] results = new int[num + 1];
        for (int i = 0; i <= num; i++) {
            results[i] = bitCount(i);
        }
        return results;
    }

    private int bitCount(int number)
    {
        int count = 0;
        while (number != 0) {
            count++;
            number = (number - 1) & number;
        }
        return count;
    }

    public static void main(String[] args)
    {
        LeetCode0338 leetcode = new LeetCode0338();
        int[] results = leetcode.countBits(5);
        for (int result : results) {
            System.out.println(result);
        }
    }
}
Math
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/673/(转载时请注明本文出处及文章链接)