How to realize bit counting in leetcod
Editor to share with you how to achieve bit counting leetcod, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!
I. the content of the topic
Given a non-negative integer num. For each number I in the 0 ≤ I ≤ num range, calculate the number of 1s in its binary number and return them as an array.
Example 1:
Enter: 2
Output: [0Jing 1jue 1]
Example 2:
Enter: 5
Output: [0pyrrine 1 pyrrine 1 pyrrine 2pr 1pime 2]
Advanced:
It is very easy to give a solution with time complexity O (n*sizeof (integer)). But can you do it with a scan in linear time O (n)?
The space complexity of the algorithm is required to be O (n).
Can you further improve the solution? Requires that you do not use any built-in functions, such as _ _ builtin_popcount in C++, to do this in C++ or any other language.
Second, the way to solve the problem
Dynamic programming, I > > 1 means that I moves one bit to the right, so the lowest bit of I will be removed, so I and I > 1 are equivalent to comparing whether the last bit is 1.
When the lowest bit of I is 0, then the number of 1 in I > > 1 is the same, because 0 is not included in the number of calculated 1.
Otherwise, the lowest bit 1 is equivalent to being erased, so the number of 1 in I > > 1 plus 1 is the number of 1 in I.
Code class Solution: def countBits (self Num: int)-> list: dp = [0 for _ in range (num + 1)] for i in range (num + 1): i_last_num = I & 1 # get the last digit of I if i_last_num = = 0: dp [I] = dp [I > > 1] else: dp [I ] = dp [I > > 1] + i_last_num return dpif _ name__ ='_ main__': s = Solution () num = 5 ans = s.countBits (num) print (ans) these are all the contents of the article "how leetcod achieves bit counting" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!