Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Given an integer n
, return an array ans
of length n + 1
such that for each i
(0 <= i <= n
), ans[i]
is the number of 1
‘s in the binary representation of i
.
Example 1:
Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10
Example 2:
Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
Constraints:
0 <= n <= 105
Follow up:
O(n log n)
. Can you do it in linear time O(n)
and possibly in a single pass?__builtin_popcount
in C++)?class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans;
// iterating fromt 0 to n
for(int i = 0; i<=n; i++)
{
// sum is initialised as 0
int sum = 0;
int num = i;
// while num not equals zero
while(num != 0)
{
// we have to count 1's in binary representation of i, therefore % 2
sum += num%2;
num = num/2;
}
// add sum to ans vector
ans.push_back(sum);
}
// return
return ans;
}
};
public int[] countBits(int num) {
int[] f = new int[num + 1];
for (int i=1; i<=num; i++) f[i] = f[i >> 1] + (i & 1);
return f;
}
def countBits(self, num: int) -> List[int]:
counter = [0]
for i in range(1, num+1):
counter.append(counter[i >> 1] + i % 2)
return counter
In our experience, we suggest you solve this Counting Bits LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Counting Bits LeetCode Solution
I hope this Counting Bits LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>