Ascending order of three integers after XOR operation
Given three distinct integers X, Y, Z. Find an integer N that after performing XOR of each element, integers must follow that X should be minimum and Z should be maximum between three integers. If possible then print the integer, Otherwise print -1.
Examples:
Input: 4, 5, 6
Output: 0
Explanation: 4 XOR 0 = 4, 5 XOR 0 = 5, 6 XOR 0 = 6, so 4 is minimum and 6 is maximum, .Input: 12, 9, 8
Output: 15
Approach: To solve the problem follow the below idea:
The approach checks if the three integers are sorted in ascending or descending order. If it is sorted in ascending order, it outputs 0, because we know that Any Number XOR 0 = That Number. If it is sorted in descending order, calculates the next positive integer of the maximum integer which is a power of 2, and prints that number -1. If the array is not sorted, it outputs -1.
- Check if the integers are sorted in ascending order by comparing X with Y and Y with Z. If it is, output 0.
- Check if the array is sorted in descending order by comparing X with Y and Y with Z. If it is, compute the next positive integer of the maximum integer which is a power of 2 minus 1 using the logarithm and power functions, and output this value.
- If the array is not sorted, output -1.
Below is the implementation of the above approach:
C++
// C++ code for the above approach:#include <bits/stdc++.h>using namespace std; void sortThreeInteger(int X, int Y, int Z, int n){ // Check if the three integers // sorted in ascending order if (X < Y && Y < Z) { // If they sorted in ascending // order, output "Yes 0" cout << 0 << endl; } // Check if the three integers are // sorted in descending order else if (X > Y && Y > Z) { // If the three integers are // sorted in descending order, // compute the smallest power of // 2 greater than the first // element minus one // Compute the logarithm of // the first element to base 2 int d = log2(X); // Compute the smallest power of // 2 greater than the logarithm int u = pow(2, d + 1); // Output "Yes" followed by // the computed value cout << u - 1 << endl; } // If the integers are not sorted, // output "No" else { cout << -1 << endl; }} // Drivers codeint main(){ int X = 12, Y = 9, Z = 8; // Function call sortThreeInteger(X, Y, Z, 3); return 0;} |
15
Time Complexity: O(1)
Auxiliary Space: O(1)



Please Login to comment...