📜  找到| A – K | = | B – K |

📅  最后修改于: 2021-04-21 23:05:41             🧑  作者: Mango

给定两个整数AB ,其中(A≠B) 。任务是找到K,使得| A – K | = | B – K | 。如果不存在这样的K ,则打印-1

例子:

方法:给定A≠B 。因此,假设A 则有以下三种情况:

  • K 这给出A – K = B – K ,得出A = B ,这是错误的。
  • K> B:这给出K – A = K – B ,这也是错误的。
  • A≤K≤B:得出K – A = B – K得出2 * K = A + B

如果A + B为奇数,则无解。如果A + B为偶数,则答案为(A + B)/ 2

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to find k such that
// |a - k| = |b - k|
int find_k(int a, int b)
{
    // If (a + b) is even
    if ((a + b) % 2 == 0)
        return ((a + b) / 2);
  
    return -1;
}
  
// Driver code
int main()
{
    int a = 2, b = 16;
  
    cout << find_k(a, b);
  
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
      
// Function to find k such that
// |a - k| = |b - k|
static int find_k(int a, int b)
{
    // If (a + b) is even
    if ((a + b) % 2 == 0)
        return ((a + b) / 2);
  
    return -1;
}
  
// Driver code
public static void main(String[] args)
{
    int a = 2, b = 16;
  
    System.out.println(find_k(a, b));
}
}
  
// This code is contributed by Code_Mech


Python3
# Python3 implementation of the approach 
  
# Function to find k such that 
# |a - k| = |b - k| 
def find_k(a, b) :
  
    # If (a + b) is even 
    if ((a + b) % 2 == 0) : 
        return ((a + b) // 2); 
  
    return -1; 
  
# Driver code 
if __name__ == "__main__" : 
  
    a = 2; b = 16; 
  
    print(find_k(a, b)); 
  
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach 
using System;
  
class GFG
{
      
// Function to find k such that
// |a - k| = |b - k|
static int find_k(int a, int b)
{
    // If (a + b) is even
    if ((a + b) % 2 == 0)
        return ((a + b) / 2);
  
    return -1;
}
  
// Driver code
public static void Main()
{
    int a = 2, b = 16;
  
    Console.Write(find_k(a, b));
}
}
  
// This code is contributed by chitranayal


输出:
9