LeetCode(338)--bit count

table of Contents

topic

338. Bit count
Given a non-negative integer num. For each number i in the range 0 ≤ i ≤ num, count the number of 1s in its binary number and return them as an array.

Example 1:

输入: 2
输出: [0,1,1]

Example 2:

输入: 5
输出: [0,1,1,2,1,2]

Advanced:

给出时间复杂度为O(n*sizeof(integer))的解答非常容易。但你可以在线性时间O(n)内用一趟扫描做到吗?
要求算法的空间复杂度为O(n)
你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount)来执行此操作。

Problem solution (Java)

Time-consuming writing

class Solution 
{
    
    
    public int[] countBits(int num) 
    {
    
    
        int[] result = new int[num + 1];
        result[0] = 0;
        for(int index = 1;index <= num;index++)
        {
    
    
            result[index] = getN(index);
        }
        return result;
    }
    //返回数字i对应的二进制中1的数目
    public int getN(int i)
    {
    
    
        int count = 0;
        int result = -1;
        while(true)
        {
    
    
            if(i == 1)
            {
    
    
                count++;
                break;
            }
            result = i % 2;
            i = i / 2;
            if(result == 1)
            {
    
    
                count++;
            }
        }
        return count;
    }
}

Advanced writing

class Solution 
{
    
    
    public int[] countBits(int num) 
    {
    
    
        int[] result = new int[num + 1];
        if(num == 0)
        {
    
    
            result[0] = 0;
            return result;
        }
        result[0] = 0;
        result[1] = 1;
        for(int index = 2;index <= num;index++)
        {
    
    
            //如果为偶数
            if(index % 2 == 0)
            {
    
    
                result[index] = result[index / 2];
            }
            //如果为奇数
            else if(index % 2 == 1)
            {
    
    
                result[index] = result[index / 2] + 1;
            }
        }
        return result;
    }
}

Guess you like

Origin blog.csdn.net/weixin_46841376/article/details/114298626