Wednesday, May 31, 2023
HomeSoftware DevelopmentDiscover the biggest palindrome XOR integer smaller than n

# Discover the biggest palindrome XOR integer smaller than n

Given an integer n, you have to discover the biggest integer m (m < n) such that m XOR n is a palindrome. If there is no such thing as a such integer, return -1.

Examples :

Enter: n = 10
Output: 5
Clarification:

• The binary illustration of 10 is 1010.
• The binary illustration of 5 is 0101.

The XOR of 10 and 5 is 1111, which is a palindrome.

Enter: n = 7
Output: 5
Clarification:

• The binary illustration of seven is 111.
• The binary illustration of three is 101.

The XOR of seven and three is 101, which is a palindrome.

Method: This may be solved with the next thought:

This may be solved by mathematical and logical observations.

• Discovering the variety of bits within the enter integer n utilizing the system numBits = log2(n) + 1.
•  It then iterates from the utmost doable worth of m all the way down to 0.
• Contained in the loop, the operate computes the XOR of m and n and checks if it’s a palindrome. To test if the XOR is a palindrome, it begins by evaluating the primary and final bits of the XOR after which strikes towards the center of the XOR, evaluating the corresponding bits at every finish.
• The loop stops as quickly because the comparability reaches the center of the XOR. If the XOR is a palindrome, the operate returns m.
• If no integer m is discovered such that m XOR n is a palindrome, the operate returns -1.

Under is the implementation of the code :

## C++

```// C++ code for the above method:
#embrace <bits/stdc++.h>
#embrace <bitset>
utilizing namespace std;

// Perform to seek out largest Integer
// forming palindrome with n
int largestPalindromeXOR(int n)
{
// Discover the variety of bits in n
int numBits = log2(n) + 1;

// Iterate from the utmost doable
// worth of m all the way down to 0
for (int m = n - 1; m >= 0; m--) {

// Compute 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 = true;
whereas (i < j) {
if (x & (1 << i)) {
if (!(x & (1 << j))) {
isPalindrome = false;
break;
}
}
else {
if (x & (1 << j)) {
isPalindrome = false;
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;
}

// Driver code
int fundamental()
{

int n = 10;

// Perform name
int largestPalXOR = largestPalindromeXOR(n);
if (largestPalXOR == -1) {
cout << "No such integer exists" << endl;
}
else {
cout << largestPalXOR << endl;
}
return 0;
}```

Time Complexity: O(n*logn)
Auxiliary House: O(1)

RELATED ARTICLES