Keira
Published on

leetCode 338.Counting Bits

Authors
  • avatar
    Name
    Keira M J
    Twitter

Problem

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

Approach

First, I thought about using a for loop to iterate over the given n and converting each i decimal number to binary to create a new array.


How to covert number to binary

Number(n).toString(2)

How to covert number to Array

Array.from(String(number))

and then use Array.reduce() for the return value from the calculation on the preceding element


Solution

var countBits = function (n) {
  let result = []
  for (let i = 0; i < n + 1; i++) {
    let temp = Number(i).toString(2)
    let num = Array.from(String(temp)).reduce((acc, cur) => Number(acc) + Number(cur))
    result.push(num)
  }

  return result
}