diff --git a/bit_manipulation/count_bits_flip.cpp b/bit_manipulation/count_bits_flip.cpp index 2ab2ce31c15..bad0399e1d3 100644 --- a/bit_manipulation/count_bits_flip.cpp +++ b/bit_manipulation/count_bits_flip.cpp @@ -45,15 +45,16 @@ std::uint64_t countBitsFlip( std::int64_t B) { // int64_t is preferred over int so that // no Overflow can be there. - int count = - 0; // "count" variable is used to count number of bits flip of the - // number A to form B in binary representation of number 'n' - A = A ^ B; - while (A) { - A = A & (A - 1); - count++; - } - return count; + int xor_value = A ^ B; // Step 1: Find XOR of start and goal + int res = 0; + + // Step 2: Count number of 1s in XOR result + while (xor_value > 0) { + res += xor_value & 1; // Increment count if last bit is 1 + xor_value >>= 1; // Right shift to check next bit + } + + return res; } } // namespace count_bits_flip } // namespace bit_manipulation