PIXELBANKv8.2.1
Menu

Counting Bits

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+1n+1, where nn is the input integer, so for n=5n = 5, the array will have 6 elements.
  • It then iterates over each number ii from 0 to nn (inclusive), converting ii to its binary representation and counting the number of 1s.
  • The binary representations and their corresponding 1s counts are as follows:
    • 010=020_{10} = 0_2 (0 ones)
    • 110=121_{10} = 1_2 (1 one)
    • 210=1022_{10} = 10_2 (1 one)
    • 310=1123_{10} = 11_2 (2 ones)
    • 410=10024_{10} = 100_2 (1 one)
    • 510=10125_{10} = 101_2 (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

Test Results

0/0
Run code to see test results.