saptarshisarkar20 / Hacktoberfest2023

This repo is for participating into the Hacktoberfest 2023
35 stars 197 forks source link

Added solution for the problem #72 #115

Closed DebapriyaJha closed 9 months ago

DebapriyaJha commented 10 months ago

Title: Calculating the Number of 1's in Binary Representation in C++

Description:

I have created a C++ code snippet that efficiently calculates the number of 1's in the binary representation of numbers from 0 to a user-specified integer n.

How It Works:

The code defines a class Bit with a member function countBits. The function takes an integer n as input and returns a vector of integers. It initializes a vector a to store the counts of 1's for each number from 0 to n.

It then iterates through the numbers from 1 to n and uses bitwise operations to calculate the number of 1's in their binary representations. Specifically, it calculates i >> 1 to obtain the count of 1's in i / 2 and (i & 1) to determine if the least significant bit is 1. These values are added together and stored in the a[i] element of the result vector.

My code follows the mentioned requirements-

Linear time complexity of O(n) Single-pass Not used any built-in function (i.e., like __builtin_popcount in C++)