Given a positive integer N, the task is to find the largest integer M such that 0 <= M < N and XOR(M, N) is an even number. If such a value of M cannot be obtained for given N, print -1.
Examples:
Input: N = 10
Output: 8
Explanation:
(10 XOR 9) = 3, so M = 9 is not possible because 3 is not an even number.
(10 XOR 8) = 2, so M = 8 is possible as it is the largest possible value of M satisfying the necessary conditions.
Input: N = 5
Output: 3
(5 XOR 4) = 1, so M = 4 is not possible because 1 is not an even number.
(5 XOR 3) = 6, so M = 3 is possible as 6 is an even number and 3 is the largest possible value of M (which is less than N).
Approach:
Following observations need to be made while solving the problem:
- An odd number represented in its binary form has 1 as its Least Significant Bit(LSB), whereas an even number represented in its binary form has 0 as its Least Significant Bit(LSB).
- While performing XOR operation, if the number of set bits is odd, then the XOR value will be 1. If the number of set bits is even, then the XOR value will be 0.
- Hence, we need to perform XOR of two odd numbers or two even numbers to obtain an even number as the result.
From the above explanation, the problem can be solved by the following steps:
- If N is odd, the largest odd number which is less than N will be N – 2.
- If N is even, the largest even number which is less than N will be N – 2.
- Hence, if N = 1, print -1 as a suitable M cannot be obtained in this case. For all other cases, print N – 2 as the answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getM( int n)
{
if (n == 1)
return -1;
else
return n - 2;
}
int main()
{
int n = 10;
int ans = getM(n);
cout << ans;
}
|
Java
import java.util.*;
class GFG{
static int getM( int n)
{
if (n == 1 )
return - 1 ;
else
return n - 2 ;
}
public static void main(String[] args)
{
int n = 10 ;
System.out.print(getM(n));
}
}
|
Python3
def getM(n):
if (n = = 1 ):
return - 1 ;
else :
return n - 2 ;
n = 10
print (getM(n))
|
C#
using System;
class GFG{
static int getM( int n)
{
if (n == 1)
return -1;
else
return n - 2;
}
static void Main()
{
int n = 10;
Console.Write(getM(n));
}
}
|
Javascript
<script>
function getM(n)
{
if (n == 1)
return -1;
else
return n - 2;
}
var n = 10;
document.write(getM(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
05 Aug, 2021
Like Article
Save Article