zoukankan      html  css  js  c++  java
  • 【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 }
  • 相关阅读:
    杭电2050
    杭电2043,小细节。。。。。
    杭电2034,坑爹的人见人爱a-b
    杭电2035--人见人爱A^B
    杭电2032--杨辉三角
    杭电2029--Palindromes _easy version(回文串)
    杭电2028--Lowest Common Multiple Plus
    NPOI大数据分批写入同个Excel
    [每日一题] OCP1z0-047 :2013-07-25 权限――角色与对象权限
    Ubuntu下安装搜狗拼音输入法
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3912220.html
Copyright © 2011-2022 走看看