## C# || Counting Bits – How To Return The Number Of 1’s In Binary Representation Of X Using C#

The following is a module with functions which demonstrates how to return the number of 1’s in binary representation of X using C#.

1. Count Bits – Problem Statement

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 ```

2. Count Bits – Solution

The following is a solution which demonstrates how return the number of 1’s in binary representation of X.

In this problem, we can see a pattern start to form.

When the current n is even, we can get the answer by dividing by 2 (e.g result[n] = result[n / 2])

When the current n is odd, we can get the answer by getting the result at previous index and adding 1 (e.g result[n] = result[n – 1] + 1)

``` 2. Level Order - Solution C# // ============================================================================ // Author: Kenneth Perkins // Date: Oct 2, 2022 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to return binary representation of X // ============================================================================ public class Solution { public int[] CountBits(int n) { var result = new int[n + 1]; result[0] = 0; for (int index = 1; index < result.Length; ++index) { if (index % 2 == 0) { result[index] = result[index / 2]; } else { result[index] = result[index - 1] + 1; } } return result; } }// http://programmingnotes.org/ 12345678910111213141516171819202122 // ============================================================================//    Author: Kenneth Perkins//    Date:   Oct 2, 2022//    Taken From: http://programmingnotes.org///    File:  Solution.cs//    Description: Demonstrates how to return binary representation of X// ============================================================================public class Solution {    public int[] CountBits(int n) {        var result = new int[n + 1];        result[0] = 0;         for (int index = 1; index < result.Length; ++index) {            if (index % 2 == 0) {                result[index] = result[index / 2];            } else {                result[index] = result[index - 1] + 1;            }        }        return result;    }}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:

``` [0,1,1] [0,1,1,2,1,2] ```