CCF试题Java-匹配相反数

import java.util.Scanner;

/**
 * 有 N 个非零且各不相同的整数。请你编一个程序求出它们中有多少对相反数(a 和 -a 为一对相反数)。 输入格式 
	第一行包含一个正整数 N。(1 ≤ N ≤ 500)。 
	第二行为 N 个用单个空格隔开的非零整数,每个数的绝对值不超过1000,保证这些整数各不相同。 输出格式 
	只输出一个整数,即这 N 个数中包含多少对相反数。

	样例输入 
	5 
	1 2 3 -1 -2 
	
	样例输出 
	2
 * @author Administrator
 *
 */
public class MatchXf {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		
		int n = sc.nextInt();
		
		int[] count = new int[1001];
		
		int temp = 0;
		for (int i = 0; i < n; i++) {
			temp = sc.nextInt();
			if(temp < 0) {
				temp = (int) Math.sqrt(temp);
				count[temp]++;
			}else {
				count[temp]++;
			}
		}
		
		int sum = 0;
		for (int i = 0; i < count.length; i++) {
			if(count[i] > 1)
				sum += count[i];
		}
		
		System.out.println(sum);
	}
}

猜你喜欢

转载自blog.csdn.net/kidchildcsdn/article/details/81051867