[Java] 338. Bit counting---learn how to convert decimal to binary! ! !

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:

Input: 2
Output: [0,1,1]
Example 2:

Input: 5
Output: [0,1,1,2,1,2]
Advanced:

It is very easy to give a solution with a time complexity of O(n*sizeof(integer)). But can you do it with one scan in linear time O(n)?
The space complexity of the algorithm is required to be O(n).
Can you further refine the solution? It is required that no built-in functions (such as __builtin_popcount in C++) are used in C++ or any other language to perform this operation.

代码:
public int[] countBits(int num) {
    
    
		int []a=new int[num+1];
		for(int i=0;i<a.length;i++) {
    
    
			a[i]=sum(i);
		}
		return a;
    }
	public int sum(int num) {
    
    
		int sum=0;
		while(num>0) {
    
    
			if(num%2==1) {
    
    
				sum++;
			}
		    num/=2;
		}	
		return sum;
	}

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/114319579
Recommended