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 | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 160 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
8 | awoo | 154 |
10 | luogu_official | 151 |
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://mirror.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