VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-two-numbers-sum-xor/

⇱ Find two numbers from their sum and XOR - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find two numbers from their sum and XOR

Last Updated : 31 Jan, 2023

Given the sum and xor of two numbers X and Y s.t. sum and xor , we need to find the numbers minimizing the value of X. Examples :

Input : S = 17
 X = 13
Output : a = 2
 b = 15

Input : S = 1870807699 
 X = 259801747
Output : a = 805502976
 b = 1065304723

Input : S = 1639
 X = 1176
Output : No such numbers exist

Variables Used: X ==> XOR of two numbers S ==> Sum of two numbers X[i] ==> Value of i-th bit in X S[i] ==> Value of i-th bit in S

A simple solution is to generate all possible pairs with given XOR. To generate all pairs, we can follow below rules.

  1. If X[i] is 1, then both a[i] and b[i] should be different, we have two cases.
  2. If X[i] is 0, then both a[i] and b[i] should be same. we have two cases.
    1. If X[i] = 0 and A[i] = 0, then a[i] = b[i] = 0. Only one possibility for this bit.
    2. If X[i] = 0 and A[i] = 1, then a[i] = b[i] = 1. Only one possibility for this bit.
    3. If X[i] = 1 and A[i] = 0, then (a[i] = 1 and b[i] = 0) or (a[i] = 0 and b[i] = 1), we can pick any of the two.
    4. If X[i] = 1 and A[i] = 1, result not possible (Note X[i] = 1 means different bits)

Let the summation be S and XOR be X.

Below is the implementation of above approach:

Output
a = 15
b = 2

Time Complexity: O(logn)

Auxiliary Space: O(1)

Comment
Article Tags: