Discover the biggest palindrome XOR integer smaller sized than n

Enhance Post

Conserve Post

Like Post

Enhance Post

Conserve Post

Like Post

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; 
.}

.} 
. 

. <

Time Intricacy: O( n * logn)
Auxiliary Area: O( 1)

Last Upgraded:
18 May, 2023

Like Post

Conserve Post

.

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: