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 | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 156 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
9 | nor | 153 |
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.me/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