We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Bit Manipulation
- Sum vs XOR
- Discussions
Sum vs XOR
Sum vs XOR
Sort by
recency
|
248 Discussions
|
Please Login in order to post a comment
sum is essentially xor except, there's the possibility of a carry with addition: 1 ^ 1 == 0, while 1 + 1 = 10. That's why you want to count the number of zeroes in the input. Once you have that, you need all the permutations of toggling those zeroes, which is 2 ** n_zeroes, or 1 << n_zeroes.
If we choose 100, which is b'110 0100, there are four zeroes, so there are 16 ways to toggle the zeroes -> 0, 1, 10, 11, 1000, 1001, 1010, 1011, 10000, 10001, 10010, 10011, 11000, 11001, 11010, 11011.
Here is my Python solution! A really clever trick is to realize that the amount is just 2 raised to the amount of 0s in the binary representation of the number.
Here is my C++ solution, you can watch the explanation here : https://youtu.be/yj0yNv6BZa8
C solution
More at https://github.com/pakbungdesu/hackerrank-problem-solving.git
Java
Pyhon