Find a value whose XOR with given number is maximum
Last Updated :
18 Apr, 2023
Given a value X, the task is to find the number Y which will give maximum value possible when XOR with X.
(Assume X to be 8 bits) Maximum possible value of X and Y is 255.
Examples:
Input: X = 2
Output: 253
Binary Representation of X = 00000010
Binary Representation of Y = 11111101
Maximum XOR value: 11111111
Input: X = 200
Output: 55
Approach: In order to ensure the maximum value of XOR, we need to set all those bits ON which are OFF in X. So for that, Y should have all bits ON which are OFF in X and OFF which are ON in X as (0^1 = 1 and 1^0 = 1). So Y should be the 1’s complement representation of X.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int calculate( int X)
{
int number_of_bits = 8;
return ((1 << number_of_bits) - 1) ^ X;
}
int main()
{
int X = 4;
cout << "Required Number is : "
<< calculate(X) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static int calculate( int X)
{
int number_of_bits = 8 ;
return (( 1 << number_of_bits) - 1 ) ^ X;
}
public static void main (String[] args) {
int X = 4 ;
System.out.println( "Required Number is : "
+calculate(X));
}
}
|
Python3
def calculate(X):
number_of_bits = 8
return (( 1 << number_of_bits) - 1 ) ^ X
if __name__ = = "__main__" :
X = 4
print ( "Required Number is:" , calculate(X))
|
C#
using System;
class GFG
{
static int calculate( int X)
{
int number_of_bits = 8;
return ((1 << number_of_bits) - 1) ^ X;
}
public static void Main ()
{
int X = 4;
Console.WriteLine( "Required Number is : " +
calculate(X));
}
}
|
PHP
<?php
function calculate( $X )
{
$number_of_bits = 8;
return ((1 << $number_of_bits ) - 1) ^ $X ;
}
$X = 4;
echo "Required Number is : " .
calculate( $X ) . "\n" ;
?>
|
Javascript
<script>
function calculate(X)
{
let number_of_bits = 8;
return ((1 << number_of_bits) - 1) ^ X;
}
let X = 4;
document.write( "Required Number is : "
+ calculate(X) + "<br>" );
</script>
|
Output:
Required Number is : 251
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...