Given x and y, we need to find smallest a and b such that
a + b = x
a xor b = y
How to solve this?
# | User | Rating |
---|---|---|
1 | ecnerwala | 3649 |
2 | Benq | 3581 |
3 | orzdevinwang | 3570 |
4 | Geothermal | 3569 |
4 | cnnfls_csy | 3569 |
6 | tourist | 3565 |
7 | maroonrk | 3531 |
8 | Radewoosh | 3521 |
9 | Um_nik | 3482 |
10 | jiangly | 3468 |
# | User | Contrib. |
---|---|---|
1 | maomao90 | 174 |
2 | awoo | 164 |
3 | adamant | 163 |
4 | TheScrasse | 159 |
5 | nor | 158 |
6 | maroonrk | 156 |
7 | -is-this-fft- | 152 |
8 | SecondThread | 147 |
9 | orz | 146 |
10 | pajenegod | 145 |
Name |
---|
Is it 1 ≤ x, y ≤ 107? If so, you can brute-force the value of a. If you decide the value of a, the value of b is determined to be x - a, and you can easily check a xor b.
But, I have two questions:
1. What is the actual constraints?
2. Smallest a and b? Which value should be minimized?
a + b can be written as (a^b) + (2 * (a&b)). So
x = y + 2 * (a&b) Which implies
a&b = (x - y) / 2.
Now can you find a, b such that their and is (x - y) / 2?
By the way, I solved this question few months back and this is the code: https://ideone.com/WmTLgr
Can you explained how we can write a + b as (a^b) + (2 * (a&b)) ?
Search for "add two numbers using bitwise operators". Also there is a similar problem in codeforces which you might be interested: http://codeforces.com/contest/635/problem/C
Another way to solve this problem to simulate the process using digit DP, it works in O(logN).
I guess constraints are x, y ≤ 1e18