TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
count_bits_flip.cpp
Go to the documentation of this file.
1
22#include <cassert>
23#include <cstdint>
24#include <iostream>
29namespace bit_manipulation {
36namespace count_bits_flip {
43std::uint64_t countBitsFlip(
44 std::int64_t A,
45 std::int64_t B) { // int64_t is preferred over int so that
46 // no Overflow can be there.
47
48 int count =
49 0; // "count" variable is used to count number of bits flip of the
50 // number A to form B in binary representation of number 'n'
51 A = A ^ B;
52 while (A) {
53 A = A & (A - 1);
54 count++;
55 }
56 return count;
57}
58} // namespace count_bits_flip
59} // namespace bit_manipulation
60
65static void test() {
66 // A = 10, B = 20 return 4
67 assert(bit_manipulation::count_bits_flip::countBitsFlip(10, 20) == 4);
68 // A = 20, B = 25 return 3
69 assert(bit_manipulation::count_bits_flip::countBitsFlip(20, 25) == 3);
70 // A = 7, B = 10 return 3
71 assert(bit_manipulation::count_bits_flip::countBitsFlip(7, 10) == 3);
72 // A = 17, B = 25 return 1
73 assert(bit_manipulation::count_bits_flip::countBitsFlip(17, 25) == 1);
74 // A = 11, B = 8 return 2
75 assert(bit_manipulation::count_bits_flip::countBitsFlip(11, 8) == 2);
76 // A = 21, B = 22 return 2
77 assert(bit_manipulation::count_bits_flip::countBitsFlip(21, 22) == 2);
78 // A = 7, B = 786 return 5
79 assert(bit_manipulation::count_bits_flip::countBitsFlip(7, 786) == 5);
80 std::cout << "All test cases successfully passed!" << std::endl;
81}
86int main() {
87 test(); // run self-test implementations
88 return 0;
89}
std::uint64_t countBitsFlip(std::int64_t A, std::int64_t B)
The main function implements count of bits flip required.
static void test()
Self-test implementations.
int main()
Main function.
Functions for the count bits flip implementation.