problem338

package
v1.6.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 23, 2021 License: MIT Imports: 0 Imported by: 0

README

< Previous                  Next >

338. Counting Bits (Medium)

Given an integer num, return an array of the number of 1's in the binary representation of every number in the range [0, num].

 

Example 1:

Input: num = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10

Example 2:

Input: num = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101

 

Constraints:

  • 0 <= num <= 105

 

Follow up:

  • It is very easy to come up with a solution with run time O(32n). Can you do it in linear time O(n) and possibly in a single pass?
  • Could you solve it in O(n) space complexity?
  • Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)?

[Bit Manipulation] [Dynamic Programming]

Similar Questions

  1. Number of 1 Bits (Easy)

Hints

Hint 1 You should make use of what you have produced already.
Hint 2 Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
Hint 3 Or does the odd/even status of the number help you in calculating the number of 1s?

Documentation

The Go Gopher

There is no documentation for this package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL