- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

#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); }

The value of n is: 7

- Related Questions & Answers
- Sum of the series Kn + ( K(n-1) * (K-1)1 ) + ( K(n-2) * (K-1)2 ) + ... (K-1)n in C++
- Find minimum x such that (x % k) * (x / k) == n in C++
- Find k-th smallest element in given n ranges in C++
- Maximum XOR using K numbers from 1 to n in C++
- Find (1^n + 2^n + 3^n + 4^n) mod 5 in C++
- Find maximum value of x such that n! % (k^x) = 0 in C++
- Count of all N digit numbers such that num + Rev(num) = 10^N - 1 in C++
- Minimum number of squares whose sum equals to given number n
- Find a positive number M such that gcd(N^M,N&M) is maximum in Python
- Find smallest number K such that K % p = 0 and q % K = 0 in C++
- Count digits in given number N which divide N in C++
- Find a number x such that sum of x and its digits is equal to given n in C++
- JavaScript - Find the smallest n digit number or greater
- Find a number x such that sum of x and its digits is equal to given n using C++.
- Smallest number that is divisible by first n numbers in JavaScript

Advertisements