.................

已知一个数组中有俩个数出现了奇数次,其余数出现偶数次,找出出现奇数次的俩个数

/**
 * @Auther: 么么
 * @Date: 2023/5/9 - 05 - 09 - 22:12
 * @Description: PACKAGE_NAME
 * @version: 1.0
 */

//已知一个数组中有俩个数出现了奇数次,其余数出现偶数次,找出出现奇数次的俩个数


public class test03 {
    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        int[] arr = {1, 5, 1, 14, 3, 3, 3, 3};
        //设其中一个数为 result1
        int result1 = 0;

        for (int n : arr) {
            result1 ^= n;
        }
        /**
         *  执行完for循环 result1= 5^14  result1 !=0
         *  5 --> 1001
         *  14 --> 1110
         *   1001
         *  ^1110
         *  ------
         *   0111
         *
         *  因为result1不等于0 ,所以转为二进制,必有一位是为 1
         *  所以要找的俩个数的二进制中 必有一位 一个数是1 一个数是0
         *  假设是第2位 一个数是1 一个数是0
         *  将数组中第2位上 是1 的做异或运算  得到其中一个数
         */
        //获得 rusult1 二进制位最右侧的1
        //result1 --->0111
        //~result1 取反  1000
        //~result1+1   1001
        //result1 & (~result1+1)
        //0111 & 1001   ->0001
        int right = result1 & (~result1 + 1);

        int result2 = 0;
        for (int n : arr) {
            //判断数组中最右侧位为1的数
            if ((right & n) == 1) {
                //让最右侧位为1的数作异或运算
                result2 ^= n;
            }
        }

        //找到了result2设为b  而result1 = a^b
        // 所以 result1 = a^b ^b =a   就得到了俩个数
        result1 = result1 ^ result2;

        System.out.println("一个数为:"+result1);
        System.out.println("另一个数为:"+result2);


    }


}

 

posted on 2023-05-09 22:51  么么^  阅读(12)  评论(0编辑  收藏  举报

Live2D