OJ 338. force buckle bit count

topic:

Given a non-negative integer num. For 0 ≤ i ≤ i, each digital num range, which calculates the number of binary digits 1 and returns them as an array.

Example 1:

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

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

Given time complexity is O (n * sizeof (integer) ) answers very easy. But you can in linear time O (n) with one pass do it?
The space requirements of the algorithm complexity is O (n).
You can further improve the solution it? Request does not use any built-in functions (e.g., in __builtin_popcount C ++) in C ++ or any other language to do this.

 

Code:

class Solution {
public:
	vector<int> countBits(int num) {
		vector<int>ans;
		ans.insert(ans.end(), 0);
		for (int i = 1; i <= num; i++)
		{
			ans.insert(ans.end(), i % 2 + ans[i / 2]);
		}
		return ans;
	}
};

 

Released 1235 original articles · won praise 682 · Views 1.72 million +

Guess you like

Origin blog.csdn.net/nameofcsdn/article/details/104220855