zoukankan      html  css  js  c++  java
  • 一个整型数组里除了两个数字之外,其他的数字都出现了两次

    题目:

    一个整型数组里除了两个数字之外,其他的数字都出现了两次

    解答:

    我们从头到尾异或数组中的每个数字,那么最终的结果是两个只出现一次数字的异或的结果,由于两个数字不一样,那么异或的结果肯定不为0,那么这个数字的二进制表示中至少有一位为1。

     1 public class Solution {
     2     public static void main(String[] args) {
     3         int[] array = {2,4,3,6,3,2,5,5};
     4         findNumsAppearOnce(array);
     5     }
     6 
     7     private static void findNumsAppearOnce(int[] array){
     8         if(array == null) {
     9             return;
    10         }
    11 
    12         int num = 0;
    13         for(int i:array) {
    14             num ^= i;
    15         }
    16 
    17         int index = findFirstBitIs1(num);
    18         int number1 = 0;
    19         int number2 = 0;
    20 
    21         for(int i:array) {
    22             if(isBit1(i, index)) {
    23                 number1 ^= i;
    24             } else {
    25                 number2 ^= i;
    26             }
    27         }
    28 
    29         System.out.println(number1);
    30         System.out.println(number2);
    31     }
    32 
    33     private static int findFirstBitIs1(int num) {
    34         int index = 0;
    35         while((num&1) == 0) {
    36             num = num >> 1;
    37             index++;
    38         }
    39 
    40         return index;
    41     }
    42 }

  • 相关阅读:
    SQL注入(转载)
    htmlTable To jpeg
    oracle 中文乱码 全变成 '靠'
    oracle 跨库查询
    oracle 备份还原数据库
    jquery 非异步读取数据
    oracle 游标 简单使用
    自增列的一种方法收藏
    oracle 导出txt 数据,excel 数据
    oracle 简单job
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10384381.html
Copyright © 2011-2022 走看看