Find smallest number n such that n XOR n+1 equals to given k in C++


Suppose we have a positive number k. We have to find the positive number n, such that XOR of n and n+1 is same as k. So if k = 7 (111), output will be 3. As 3 (011), and 3 + 1 = 4 (100), so 011 XOR 100 = 111 (7)

There are two possible cases. Consider n is even. The last bit of n = 0. Then the last bit of n + 1 = 1. Rest of the bits are same. So XOR will be 1, when n is odd, last bit 1, and last bit of n + 1 bit is 0. But in this case, more bits which differ due to carry. The carry continues to propagate to left till we get first 0 bit. So n XOR n + 1, will be 2^i -1, where i is the position of first 0 bit in n from left. So we can say that if k is of the form 2^i – 1, the answer will be k/2.

Example

 Live Demo

#include<iostream>
using namespace std;
int findNValue(int k) {
   if (k == 1)
      return 2;
   if (((k + 1) & k) == 0)
      return k / 2;
      return -1;
}
int main() {
   int k = 15;
   cout << "The value of n is: " << findNValue(k);
}

Output

The value of n is: 7

Updated on: 18-Dec-2019

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements