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
|
251 Discussions
|
Please Login in order to post a comment
long sumXor(long n) { int c = 0; c = popcount((~n)&large(n)); return (1ULL<<c); }
also wrote the popcount function for 128 bit using parallel bit shifting and counting (spam checker isnt allowing long code pasting)
long sumXor(long n) { long result=1; while(n){ if((n&1)==0)result*=2; n>>=1; } return result; }
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.