【HackerRank】Lonely Integer

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 }
复制代码

 

posted @   SunshineAtNoon  阅读(283)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示