码迷,mamicode.com
首页 > 其他好文 > 详细

【HackerRank】Lonely Integer

时间:2014-08-14 13:55:18      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   java   io   strong   for   ar   

There are N integers in an array A. All but one integer occur in pairs. Your task is to find out the number that occurs only once.

Input Format

The first line of the input contains an integer N indicating number of integers. 
The next line contains N space separated integers that form the array A.

Constraints

1 <= N < 100 
N % 2 = 1 ( N is an odd number ) 
0 <= A[i] <= 100, ∀ i ∈ [1, N]

Output Format

Output S, the number that occurs only once.


 

常见的题:数组中除了一个数,其他数都是成对出现的。要求找出只出现了一次的这个数。

利用a xor a = 0 和 0 xor a = a这两个公式,设置一个数answer初始化为0,然后依次和数组中每个数异或,最后answer中存储的就是答案了。

代码如下:

 1 import java.io.*;
 2 import java.util.*;
 3 import java.text.*;
 4 import java.math.*;
 5 import java.util.regex.*;
 6 
 7 public class Solution {
 8 static int lonelyinteger(int[] a) {
 9     int answer = 0;
10     for(int i = 0;i < a.length;i++)
11         answer = answer ^ a[i];
12     return answer;
13 
14     }
15 public static void main(String[] args) {
16         Scanner in = new Scanner(System.in);
17         int res;
18         
19         int _a_size = Integer.parseInt(in.nextLine());
20         int[] _a = new int[_a_size];
21         int _a_item;
22         String next = in.nextLine();
23         String[] next_split = next.split(" ");
24         
25         for(int _a_i = 0; _a_i < _a_size; _a_i++) {
26             _a_item = Integer.parseInt(next_split[_a_i]);
27             _a[_a_i] = _a_item;
28         }
29         
30         res = lonelyinteger(_a);
31         System.out.println(res);
32         
33     }
34 }

 

【HackerRank】Lonely Integer,布布扣,bubuko.com

【HackerRank】Lonely Integer

标签:style   blog   color   java   io   strong   for   ar   

原文地址:http://www.cnblogs.com/sunshineatnoon/p/3912220.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!