You are given a positive number k, we need to find a positive integer n, such that XOR of n and n+1 is equal to k. If no such n exist then print -1.
Input : 3 Output : 1 Input : 7 Output : 3 Input : 6 Output : -1
Below are two cases when we do n XOR (n+1) for a number n.
Case 1 : n is even. Last bit of n is 0 and last bit of (n+1) is 1. Rest of the bits are same in both. So XOR would always be 1 if n is even.
Case : n is odd Last bit in n is 1. And in n+1, last bit is 0. But in this case there may be more bits which differ due to carry. The carry continues to propagate to left till we find first 0 bit. So n XOR n+1 will we 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 form 2^i-1 then we will have our answer as k/2.
Finally our steps are:
If we have k=1, answer = 2 [We need smallest positive n] Else If k is of form 2^i-1, answer = k/2, else, answer = -1
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Smallest number greater or equals to N such that it has no odd positioned bit set
- Find the number of pairs such that their gcd is equals to 1
- Find the smallest number whose digits multiply to a given number n
- Find smallest number K such that K % p = 0 and q % K = 0
- Given a number, find the next smallest palindrome
- Find smallest permutation of given number
- Find the kth smallest number with sum of digits as m
- Find the smallest number with n set and m unset bits
- Find the smallest number X such that X! contains at least Y trailing zeros.
- Find the k-th smallest divisor of a natural number N
- Find Nth smallest number that is divisible by 100 exactly K times
- Find smallest positive number Y such that Bitwise AND of X and Y is Zero
- Find the smallest positive number which can not be represented by given digits
- Find kth smallest number in range [1, n] when all the odd numbers are deleted
- Find the smallest positive number missing from an unsorted array | Set 3