Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
count_of_set_bits.cpp File Reference

Implementation to count sets bits in an integer. More...

#include <cassert>
#include <iostream>
#include <vector>
Include dependency graph for count_of_set_bits.cpp:

Namespaces

namespace  bit_manipulation
 for std::vector
 
namespace  count_of_set_bits
 Functions for the count sets bits implementation.
 

Functions

std::uint64_t bit_manipulation::count_of_set_bits::countSetBits (int n)
 The main function implements set bit count. More...
 
static void test ()
 Self-test implementations. More...
 
int main ()
 Main function. More...
 

Detailed Description

Implementation to count sets bits in an integer.

We are given an integer number. Let’s say, number. The task is to first calculate the binary digit of a number and then calculate the total set bits of a number.

Set bits in a binary number is represented by 1. Whenever we calculate the binary number of an integer value it is formed as the combination of 0’s and 1’s. So digit 1 is known as a set bit in computer terms. Time Complexity: O(log n) Space complexity: O(1)

Author
Swastika Gupta

Function Documentation

◆ countSetBits()

std::uint64_t bit_manipulation::count_of_set_bits::countSetBits ( int  n)

The main function implements set bit count.

Parameters
nis the number whose set bit will be counted
Returns
the count of the number set bit in the binary representation of n
41 {
42 int count = 0; // "count" variable is used to count number of 1's in binary
43 // representation of the number
44 while (n != 0) {
45 count += n & 1;
46 n = n >> 1; // n=n/2
47 }
48 return count;
49}
Here is the call graph for this function:

◆ main()

int main ( void  )

Main function.

Returns
0 on exit
77 {
78 test(); // run self-test implementations
79 return 0;
80}
static void test()
Self-test implementations.
Definition: count_of_set_bits.cpp:57
Here is the call graph for this function:

◆ test()

static void test ( )
static

Self-test implementations.

Returns
void
57 {
58 // n = 4 return 1
59 assert(bit_manipulation::count_of_set_bits::countSetBits(4) == 1);
60 // n = 6 return 2
61 assert(bit_manipulation::count_of_set_bits::countSetBits(6) == 2);
62 // n = 13 return 3
63 assert(bit_manipulation::count_of_set_bits::countSetBits(13) == 3);
64 // n = 9 return 2
65 assert(bit_manipulation::count_of_set_bits::countSetBits(9) == 2);
66 // n = 15 return 4
67 assert(bit_manipulation::count_of_set_bits::countSetBits(15) == 4);
68 // n = 25 return 3
69 assert(bit_manipulation::count_of_set_bits::countSetBits(25) == 3);
70 std::cout << "All test cases successfully passed!" << std::endl;
71}
T endl(T... args)
Here is the call graph for this function: