1. 程式人生 > >《程序員代碼面試指南》第七章 位運算 在其他數都出現偶數次的數組中找到出現奇數次的數

《程序員代碼面試指南》第七章 位運算 在其他數都出現偶數次的數組中找到出現奇數次的數

return png 一個數 src code 面試指南 代碼 string des

題目

在其他數都出現偶數次的數組中找到出現奇數次的數

java代碼

package com.lizhouwei.chapter7;

/**
 * @Description: 在其他數都出現偶數次的數組中找到出現奇數次的數
 * @Author: lizhouwei
 * @CreateDate: 2018/4/28 21:02
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter7_5 {

    //在其他數都出現偶數次的數組中找到出現奇數次的數
    public int getOnce(int[] arr) {
        int once = 0;
        for (int i = 0; i < arr.length; i++) {
            once = once ^ arr[i];
        }
        return once;
    }

    //在其他數都出現偶數次的數組中找到出現奇數次的數
    public int getTwo(int[] arr) {
        int once = 0;
        for (int i = 0; i < arr.length; i++) {
            once = once ^ arr[i];
        }
        int rightOne = once & (~once + 1);//取最左的第一個出現1的位數
        int one = once;
        for (int i = 0; i < arr.length; i++) {
            if ((rightOne & arr[i]) != 0) {
                one = one ^ arr[i];
            }
        }
        System.out.print("第一個數:" + one);
        System.out.println(";第二個數:" + (once ^ one));
        return once;
    }

    //測試
    public static void main(String[] args) {
        Chapter7_5 chapter = new Chapter7_5();
        int[] arr = {1, 1, 2, 3, 3, 4, 4, 5, 5};
        int reslt = chapter.getOnce(arr);
        System.out.print("{1,1,2,3,3,4,4,5,5}中");
        System.out.println("只出現一次的數為:" + reslt);
        int[] arr1 = {1, 1, 2, 3, 3, 4, 5, 5};
        System.out.print("{1,1,2,3,3,4,5,5}中");
        chapter.getTwo(arr1);
    }
}

結果

技術分享圖片

《程序員代碼面試指南》第七章 位運算 在其他數都出現偶數次的數組中找到出現奇數次的數