如何找到数字数组的异或值

how to find the xor value of an array of numbers

我想知道一个数字中所有数字出现的频率是否相同。我使用了一个大小为 10 的数字数组(数字 0-9)并用每个数字的频率对其进行了初始化。

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];
}

如何求异或值? 它应该 return 0 表示所有非零元素都相等。

如果你"want to find if frequency of all digits in a number is same",那么你应该比较元素,而不是对它们进行异或...

public boolean isAllTheSame(int[] dig)
{
  int ans = dig[0];
  for ( int a = 1; a < 10; ++a )
  {
    if ( dig[a] != 0 )
    {
      if ( dig[a] != ans )
        return false;
      ans = dig[a];
    }
  }
  return true;
}

这将解决您的第一个问题 "check same frequency" :

int value = 2241133;
String[] digits = String.valueOf(value).split("");
boolean res = true;
int initFreq = Collections.frequency(Arrays.asList(digits), digits[0]);
for (String i : digits) {
    res = res && (Collections.frequency(Arrays.asList(digits), i) == initFreq);
    if (!res) {
        break;
    }
}
System.out.println(res);

如 int 注释所述,XOR 对此不起作用;但是,您可以使用 HashSet 来解决这个问题:

示例

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");