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.
- Sum vs XOR
- Discussions
Sum vs XOR
Sum vs XOR
Sort by
recency
|
48 Discussions
|
Please Login in order to post a comment
The 'n can be up to 10^5' information in the problem description suggests that we need to think a non-brute-force approach here.
So, thinking this through... from the example
10 (decimal) = 1010 (binary) ... has solutions ... 0 1 100 0101
Which means that we're looking for all the permutation of numbers with '1s' in the '0s' of the binary representation of the input number.
The 'n can be up to 10^5' information in the problem description suggests that we need to think a non-brute-force approach here.
So, thinking this through... from the example
10 (decimal) = 1010 (binary) ... has solutions ... 0 1 100 0101
Which means that we're looking for all the permutation of numbers with '1s' in the '0s' of the binary representation of the input number.
` def sumXor(n): if n == 0: return 1
` def sumXor(n): if n == 0: return 1
After we calculate a few examples of addition and XOR on paper, we will conclude that x+n = x xor n only if there is no carry forwarded to the next digit (in binary) when we do addition. In other words, we are only interested in x's which don't have 1s in a position where n has it. The answer is then the number of numbers we can create by filling with either 0 or 1 the 0s in n. To calculate this, we firstly count the numbers of 0s in n. The final answer is the 2 to the power of the # of 0s in n.
Java
Python3
**Python 3 **
We have
int.bit_length
to calculate number of digits in binary andint.bit_count
to calculate number of ones. So we can solve this pretty easily.