📜  找出最小的数字n,以使n XOR n + 1等于给定的k。

📅  最后修改于: 2021-05-25 10:44:31             🧑  作者: Mango

给定一个正数k,我们需要找到一个正整数n,以使n和n + 1的XOR等于k。如果不存在这样的n,则打印-1。
例子:

Input : 3
Output : 1

Input : 7
Output : 3

Input : 6
Output : -1

以下是两种情况,当我们对数字n进行n XOR(n + 1)运算时。
情况1:n是偶数。 n的最后一位为0,(n + 1)的最后一位为1。因此,如果n为偶数,则XOR始终为1。
情况:n为奇数n的最后一位为1,n + 1的最后一位为0。但是在这种情况下,可能会有更多的位因进位而不同。进位继续向左传播,直到找到第一个0位。所以n XOR n + 1将是2 ^ i-1,其中i是n从左开始的第一个0位的位置。因此,我们可以说,如果k的形式为2 ^ i-1,则答案将为k / 2。
最后,我们的步骤是:

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
C++
// CPP to find n such that XOR of n and n+1
// is equals to given n
#include 
using namespace std;
 
// function to return the required n
int xorCalc(int k)
{
    if (k == 1)
        return 2;
     
    // if k is of form 2^i-1
    if (((k + 1) & k) == 0)
        return k / 2;
 
    return 1;
}
 
// driver program
int main()
{
    int k = 31;
    cout << xorCalc(k);
    return 0;
}


Java
// Java to find n such that XOR of n and n+1
// is equals to given n
class GFG
{
     
    // function to return the required n
    static int xorCalc(int k)
    {
        if (k == 1)
            return 2;
         
        // if k is of form 2^i-1
        if (((k + 1) & k) == 0)
            return k / 2;
     
        return 1;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int k = 31;
         
        System.out.println(xorCalc(k));
    }
}
 
// This code is contributed by Anant Agarwal.


Python3
# python to find n such that
# XOR of n and n+1 is equals
# to given n
 
# function to return the
# required n
def xorCalc(k):
    if (k == 1):
        return 2
     
    # if k is of form 2^i-1
    if (((k + 1) & k) == 0):
        return k / 2
 
    return 1;
 
 
# driver program
k = 31
print(int(xorCalc(k)))
 
# This code is contributed
# by Sam007


C#
// C# to find n such that XOR
// of n and n+1 is equals to
// given n
using System;
 
class GFG
{
     
    // function to return the required
    // n
    static int xorCalc(int k)
    {
        if (k == 1)
            return 2;
         
        // if k is of form 2^i-1
        if (((k + 1) & k) == 0)
            return k / 2;
     
        return 1;
    }
     
    // Driver code
    public static void Main ()
    {
        int k = 31;
         
        Console.WriteLine(xorCalc(k));
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


输出:

15