Offered an integer n, you require to discover the biggest integer m ( m < < n) such that m XOR n is a palindrome. If there is no such integer, return -1.
Examples:
Input: n = 10
Output: 5
Description:
- The binary representation of 10 is 1010.
- The binary representation of 5 is 0101.
The XOR of 10 and 5 is 1111, which is a palindrome.
Input: n = 7
Output: 5
Description:
- The binary representation of 7 is 111.
- The binary representation of 3 is 101.
The XOR of 7 and 3 is 101, which is a palindrome.
Method: This can be fixed with the following concept:
This can be fixed by mathematical and rational observations.
- Discovering the variety of bits in the input integer n utilizing the formula numBits = log2( n) + 1
- It then repeats from the optimum possible worth of m to 0.
- Inside the loop, the function calculates the XOR of m and n and checks if it is a palindrome. To inspect if the XOR is a palindrome, it begins by comparing the very first and last littles the XOR and after that approaches the middle of the XOR, comparing the matching bits at each end.
- The loop stops as quickly as the contrast reaches the middle of the XOR. If the XOR is a palindrome, the function returns m.
- If no integer m is discovered such that m XOR n is a palindrome, the function returns -1.
Below is the execution of the code:
C++
// C++ code for the above method:
. #include < bits/stdc++. h>
>
. #include < bitset>
>
. utilizing namespace sexually transmitted disease;
.
.// Function to discover biggest Integer
.// forming palindrome with n
. int largestPalindromeXOR (int n)
.
{
.// Discover the variety of bits in n
. int numBits= log2( n) + 1;
.
.// Repeat from the optimum possible
.// worth of m to 0
. for( int m = n - 1; m >>= 0; m--) {
.
.// Calculate the XOR of m and n
.
int x =m ^ n;
.
.// Examine if the XOR of m and n
.
// is a palindrome
.
int i = 0, j= numBits-
1
;
.
&. bool isPalindrome= real;
.
while (i < j) & {
.
if( x &( 1 < < i)) {
.
if(!( x &( 1 < < j))
) {
.
.
isPalindrome= incorrect;<
.
break;
.
}
.
}
.
else {
. if (x & (1 < < j) ){
. isPalindrome= incorrect;
. break;
.
}
.
}
.
i + +;
.
j--;
.
}
.
.// If the XOR of m and n is
a
.
/
/ palindrome, return m
.
if( isPalindrome) {
.
. return m;
.}
.}
.
. </ If no such integer is discovered,
.// return -1
.
return -1;
.
}
.
.// Motorist code
. << int primary ()
.
{
.
. int n = 10;
.
.// Function call
. int largestPalXOR = largestPalindromeXOR( n);
. if (largestPalXOR = = -1) {
. cout < < "No such integer exists" < < endl;
.}
. else {
. cout < < largestPalXOR < < endl;
.}
. return 0;
.}
Time Intricacy: O( n * logn)
Auxiliary Area: O( 1)
.