Search code examples
javaxorboolean-operations

How to XOR n same numbers?


I want to XOR number k with itself n time. Easiest way is to XOR it with itself n time in a loop. Is there a better way?

int t = k;
for(int i = 0; i < n; i++) k = k ^ t;

Solution

  • XORing N copies of K together produces K if N is odd and 0 if N is even. K ^ K == 0, 0 ^ K == K, and it just alternates between those results with every additional K. (Your code is currently XORing n+1 copies of k together, which I'm guessing is a mistake.)

    int result = (n % 2 == 1) ? k : 0;