Problem description
There are N non-0 integers that are not identical. Please make up a program to find out how many pairs of opposite numbers are in them (a and-A are pairs of opposite numbers).
Input format
The first line consists of a positive integer N. (1≤n≤500).
The second behavior N a non-0 integer separated by a single space, the absolute value of each number does not exceed 1000, guaranteeing that the integers are different.
Output format
Only one integer is output, that is, how many pairs of opposite numbers are included in the N number.
Sample input
5
1 2 3-1-2
Sample output
2
-----------------------------------------------------------------------------------------
Solution 1: (My)
Import Java.util.scanner;public class Invnum {public static void main (string[] args) { //main alt+/scanner sc=new Scan NER (system.in); int n=sc.nextint (); int[] a=new int[n];for (int i=0;i<n;i++) {a[i]=sc.nextint ();} int result=0;for (int i=0;i<n;i++) {for (int j=i+1;j<n;j++) {if (a[i]+a[j]==0) {result+=1;break;}}} SYSTEM.OUT.PRINTLN (result);}}
The range of input numbers is not considered and the maximum value that n should get.
Solution 2: Refer to someone else's program, using Java-compiled
Import Java.util.scanner;public class Invnum2{public static void Main (string[] args) {new InvNum2 (). run (); public void Run () {Scanner sc=new Scanner (system.in); int n;n=sc.nextint (); int[] count=new int[1001];for (int i=0;i<n; i++) {++count[sc.nextint () +500]; Input data range is -500~500, not enough requirements }int ans=0;for (int i=0;i<=500;i++) { //up to 500 numbers ans+=math.min (Count[500+i], Count[500-i]);//The number in brackets indicates the size of the number (absolute value is less than +)}system.out.println (ans);}}
Looked at the long time only slightly to understand, indeed is wonderful.
The road long its repair far XI, I will go up and down and quest.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
CCF title: Opposite number