Search code examples
javaarraysxor

how to find the xor value of an array of numbers


I want to find if frequency of all digits in a number is same. I used a digit array of size 10 (digit 0-9) and initialized it with the frequency of every digit.

eg: 221133
dig[] = {0,2,2,2,0,0,0,0,0,0};
and 
ans = dig[0];
for(a=1;a<10;a++)
{
    if(dig[a]!=0)
        ans = ans ^ dig[a];
}

How to find the xor value? it should return 0 meaning all non-zero elements are equal.


Solution

  • As mentioned int comments, XOR will not work for this; however, you can use a HashSet to solve this:

    Example:

    int [] dig = {0,2,2,2,0,0,0,0,0,0};
    
    Set<Integer> set = new HashSet<>();
    
    for (int d : dig)
    {
        if (d != 0)
            set.add(d);
    }
    
    // check for less than 2 since 1=only 1 val, and 0=no values other than 0
    if (set.size() < 2)
        System.out.println("All values are the same");
    else
        System.out.println("Not all values are the same");