给定两个数字和 。在方程中找到X和Y的值。
- A = X + Y
- B = X或Y
任务是使X尽可能最小。如果找不到X和Y的有效值,则打印-1。
例子:
Input : A = 12, B = 8
Output : X = 2, Y = 10
Input : A = 12, B = 9
Output : -1
让我们看一下X中的某个位等于1。如果Y中的相应位等于0,则可以交换这两个位,从而减少X并增加Y,而无需更改它们的和和Xor。我们可以得出结论,如果X中的某个位等于1,则Y中的相应位也等于1。因此,Y = X +B。考虑到X + Y = X + X + B = A,则1可以获得以下公式来查找X和Y:
- X =(A – B)/ 2
- Y = X + B =(A + B)/ 2
还应该注意的是,如果A 或A和B的奇偶校验不同,则答案不存在,输出为-1。如果X和(A – X)不等于X,则答案也为-1。
下面是上述方法的实现:
C++
// CPP program to find the values of
// X and Y using the given equations
#include
using namespace std;
// Function to find the
// values of X and Y
void findValues(int a, int b)
{
// base condition
if ((a - b) % 2 == 1) {
cout << "-1";
return;
}
// required answer
cout << (a - b) / 2 << " " << (a + b) / 2;
}
// Driver Code
int main()
{
int a = 12, b = 8;
findValues(a, b);
return 0;
}
Java
// Java program to find the values of
// X and Y using the given equations
import java.io.*;
class GFG
{
// Function to find the
// values of X and Y
static void findValues(int a, int b)
{
// base condition
if ((a - b) % 2 == 1)
{
System.out.println ("-1");
return;
}
// required answer
System.out.println (((a - b) / 2)+ " " +
((a + b) / 2));
}
// Driver Code
public static void main (String[] args)
{
int a = 12, b = 8;
findValues(a, b);
}
}
// This code is contributed by ajit...
Python3
# Python3 program to find the values of
# X and Y using the given equations
# Function to find the values of X and Y
def findValues(a, b):
# base condition
if ((a - b) % 2 == 1):
print("-1");
return;
# required answer
print((a - b) // 2, (a + b) // 2);
# Driver Code
a = 12; b = 8;
findValues(a, b);
# This code is contributed
# by Akanksha Rai
C#
// C# program to find the values of
// X and Y using the given equations
using System;
class GFG
{
// Function to find the
// values of X and Y
static void findValues(int a, int b)
{
// base condition
if ((a - b) % 2 == 1)
{
Console.Write ("-1");
return;
}
// required answer
Console.WriteLine(((a - b) / 2)+ " " +
((a + b) / 2));
}
// Driver Code
static public void Main ()
{
int a = 12, b = 8;
findValues(a, b);
}
}
// This code is contributed by @Tushil..
PHP
Javascript
输出:
2 10
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。