📘
Counting Bits
EasyBit Manipulation
Given an integer n, return an array of length n+1 where ans[i] is the number of 1s in the binary representation of i.
Example:
Input:
5
Output:
0 1 1 2 1 2
Reasoning:
- The function generates an array of length n+1, where n is the input integer, so for n=5, the array will have 6 elements.
- It then iterates over each number i from 0 to n (inclusive), converting i to its binary representation and counting the number of 1s.
- The binary representations and their corresponding 1s counts are as follows:
- 010=02 (0 ones)
- 110=12 (1 one)
- 210=102 (1 one)
- 310=112 (2 ones)
- 410=1002 (1 one)
- 510=1012 (2 ones)
- The final output is an array containing these counts in order:
[0, 1, 1, 2, 1, 2].
Constraints:
- 0 <= n <= 10^5
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.