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 | jiangly | 3976 |
2 | tourist | 3815 |
3 | jqdai0815 | 3682 |
4 | ksun48 | 3614 |
5 | orzdevinwang | 3526 |
6 | ecnerwala | 3514 |
7 | Benq | 3482 |
8 | hos.lyric | 3382 |
9 | gamegame | 3374 |
10 | heuristica | 3357 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | -is-this-fft- | 165 |
3 | Um_nik | 161 |
3 | atcoder_official | 161 |
5 | djm03178 | 157 |
6 | Dominater069 | 156 |
7 | adamant | 154 |
8 | luogu_official | 152 |
9 | awoo | 151 |
10 | TheScrasse | 148 |
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.net/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