TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
count_of_set_bits.cpp
Go to the documentation of this file.
1
18#include <cassert>
19#include <cstdint>
20#include <iostream>
25namespace bit_manipulation {
32namespace count_of_set_bits {
38std::uint64_t countSetBits(
39 std ::int64_t n) { // int64_t is preferred over int so that
40 // no Overflow can be there.
41
42 int count = 0; // "count" variable is used to count number of set-bits('1')
43 // in binary representation of number 'n'
44 while (n != 0) {
45 ++count;
46 n = (n & (n - 1));
47 }
48 return count;
49 // Why this algorithm is better than the standard one?
50 // Because this algorithm runs the same number of times as the number of
51 // set-bits in it. Means if my number is having "3" set bits, then this
52 // while loop will run only "3" times!!
53}
54} // namespace count_of_set_bits
55} // namespace bit_manipulation
56
57static void test() {
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 // n = 97 return 3
71 assert(bit_manipulation::count_of_set_bits::countSetBits(97) == 3);
72 // n = 31 return 5
73 assert(bit_manipulation::count_of_set_bits::countSetBits(31) == 5);
74 std::cout << "All test cases successfully passed!" << std::endl;
75}
80int main() {
81 test(); // run self-test implementations
82 return 0;
83}
std::uint64_t countSetBits(std ::int64_t n)
The main function implements set bit count.
int main()
Main function.
Functions for the count sets bits implementation.