Tuesday, July 11, 2017

Find only non-duplicate number in an array


public class FindNonDuplicateNumber {

    
    /*
        Problem: Given array of integer every element appears twice except one find that number
        Solution: Take xor of all the numbers, the numbers that appear twice will cancel out each
        other only number that would remain is the number that appears only once
     */
    public int findNumber(int[] number){
        int result = 0;
        for(int i = 0; i < number.length ;i++){
            result = result ^ number[i];
        }
        return result;
    }
}

No comments:

Post a Comment