Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updated code #2922

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions bit_manipulation/count_bits_flip.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down