给定值X,任务是找到与Y进行XOR运算时将给出最大值的数字Y。
(假设X为8位)X和Y的最大可能值为255。
例子:
Input: X = 2
Output: 253
Binary Representation of X = 00000010
Binary Representation of Y = 11111101
Maximum XOR value: 11111111
Input: X = 200
Output: 55
方法:为了确保XOR的最大值,我们需要将X中所有OFF的位设置为ON。为此,Y应该将X中OFF的所有位ON和X中ON的所有位设为(0 ^ 1 = 1和1 ^ 0 = 1)。因此,Y应该是X的1的补码表示。
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function To Calculate Answer
int calculate(int X)
{
// Find number of bits in the given integer
int number_of_bits = 8;
// XOR the given integer with poe(2,
// number_of_bits-1 and print the result
return ((1 << number_of_bits) - 1) ^ X;
}
// Driver Code
int main()
{
int X = 4;
cout << "Required Number is : "
<< calculate(X) << endl;
return 0;
}
Java
// Java implementation of the above approach
import java.io.*;
class GFG {
// Function To Calculate Answer
static int calculate(int X)
{
// Find number of bits in the given integer
int number_of_bits = 8;
// XOR the given integer with poe(2,
// number_of_bits-1 and print the result
return ((1 << number_of_bits) - 1) ^ X;
}
// Driver Code
public static void main (String[] args) {
int X = 4;
System.out.println( "Required Number is : "
+calculate(X));
}
}
// This code is contributed by shs..
Python3
# Python3 implementation of the above approach
# Function To Calculate Answer
def calculate(X):
# Find number of bits in the given integer
number_of_bits = 8
# XOR the given integer with poe(2,
# number_of_bits-1 and print the result
return ((1 << number_of_bits) - 1) ^ X
# Driver Code
if __name__ == "__main__":
X = 4
print("Required Number is:", calculate(X))
# This code is contributed by Rituraj Jain
C#
// C# implementation of the above approach
using System;
class GFG
{
// Function To Calculate Answer
static int calculate(int X)
{
// Find number of bits in
// the given integer
int number_of_bits = 8;
// XOR the given integer with poe(2,
// number_of_bits-1 and print the result
return ((1 << number_of_bits) - 1) ^ X;
}
// Driver Code
public static void Main ()
{
int X = 4;
Console.WriteLine("Required Number is : " +
calculate(X));
}
}
// This code is contributed by shs..
PHP
输出:
Required Number is : 251