6. Opposite numbers

  1. Opposite number
    Problem description
    There are N non-zero and different integers. Please make a program to find out how many pairs of opposite numbers are in them (a and -a are a pair of
    opposite numbers).
    Input format The
    first line contains a positive integer N. (1 ≤ N ≤ 500).
    The second line is N non-zero integers separated by a single space, and the absolute value of each number does not exceed 1000, to ensure that these integers are
    different.
    Output format
    Only an integer is output, that is, how many pairs of opposite numbers are contained in these N numbers.
    Sample input
    5
    1 2 3 -1 -2
    Sample output
    2
    Method 1:
#include <bits/stdc++.h>

using namespace std;

int main()
{
    
    
    int a[501];
    int n, t, sum = 0;
    cin>>n;
    for(int i = 0; i < n; i++)
        cin>>a[i];
    for(int j = 0; j < n; j++)
    {
    
    
        t = a[j];
        for(int i = 0; i < n; i++)
        {
    
    
            if(t == -a[i])
                sum++;
        }
    }
    cout<<sum / 2;
    return 0;
}

Method 2:

#include <bits/stdc++.h>

using namespace std;

int main()
{
    
    
    int a[501];
    int n, sum = 0;
    cin>>n;
    for(int i = 0; i < n; i++)
        cin>>a[i];
    for(int j = 0; j < n; j++)
        for(int i = j + 1; i < n; i++)
            if(a[i] + a[j] == 0)
                sum++;
    cout<<sum;
    return 0;
}

Guess you like

Origin blog.csdn.net/KO812605128/article/details/113360842