给定一个数组整数,任务是找到另一个整数这样,如果从数字中分别减去数组的所有元素 ,则所有差异的总和应加到0。如果存在任何这样的整数,则打印的值 ,否则打印 。
例子
Input: arr[] = {1, 2, 3}
Output: 2
Explanation:
Substracting all the elements of arrays from 2,
The sum of difference is:
1 + 0 + (-1) = 0.
解决方案:想法是计算数组的总和,然后将其除以数组的大小。如果数组的总和可以完全按其大小整除,则从该除法运算获得的商将是所需的隐藏数。
下面是上述想法的实现:
C++
// C++ Program to find the
// hidden number
#include
using namespace std;
// Driver Code
int main() {
// Getting the size of array
int n = 3;
// Getting the array of size n
int a[] = { 1, 2, 3 };
// Solution
int i = 0;
// Finding sum of the array elements
long sum = 0;
for (i = 0; i < n; i++) {
sum += a[i];
}
// Dividing sum by size n
long x = sum / n;
// Print x, if found
if (x * n == sum)
cout<
Java
// Java Program to find the
// hidden number
public class GFG {
// Driver Code
public static void main(String args[])
{
// Getting the size of array
int n = 3;
// Getting the array of size n
int a[] = { 1, 2, 3 };
// Solution
int i = 0;
// Finding sum of the array elements
long sum = 0;
for (i = 0; i < n; i++) {
sum += a[i];
}
// Dividing sum by size n
long x = sum / n;
// Print x, if found
if (x * n == sum)
System.out.println(x);
else
System.out.println("-1");
}
}
Python 3
# Python 3 Program to find the
# hidden number
# Driver Code
if __name__ == "__main__":
# Getting the size of array
n = 3
# Getting the array of size n
a = [ 1, 2, 3 ]
# Solution
i = 0
# Finding sum of the .
# array elements
sum = 0
for i in range(n):
sum += a[i]
# Dividing sum by size n
x = sum // n
# Print x, if found
if (x * n == sum):
print(x)
else:
print("-1")
# This code is contributed
# by ChitraNayal
C#
// C# Program to find the
// hidden number
using System;
class GFG
{
// Driver Code
public static void Main()
{
// Getting the size of array
int n = 3;
// Getting the array of size n
int []a = { 1, 2, 3 };
// Solution
int i = 0;
// Finding sum of the
// array elements
long sum = 0;
for (i = 0; i < n; i++)
{
sum += a[i];
}
// Dividing sum by size n
long x = sum / n;
// Print x, if found
if (x * n == sum)
Console.WriteLine(x);
else
Console.WriteLine("-1");
}
}
// This code is contributed
// by inder_verma
PHP
输出:
2