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 | tourist | 3880 |
2 | jiangly | 3669 |
3 | ecnerwala | 3654 |
4 | Benq | 3627 |
5 | orzdevinwang | 3612 |
6 | Geothermal | 3569 |
6 | cnnfls_csy | 3569 |
8 | jqdai0815 | 3532 |
9 | Radewoosh | 3522 |
10 | gyh20 | 3447 |
# | User | Contrib. |
---|---|---|
1 | awoo | 161 |
2 | maomao90 | 160 |
3 | adamant | 156 |
4 | maroonrk | 153 |
5 | -is-this-fft- | 148 |
5 | atcoder_official | 148 |
5 | SecondThread | 148 |
8 | Petr | 147 |
9 | nor | 144 |
9 | TheScrasse | 144 |
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