[Hacker Rank] Xor-sequence

Xor-sequence

  • Time : O(1)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
// prefix xor 0 ... n
long helper(long n) {
auto m = n % 8;
if(m <= 1) return n;
if(m <= 3) return 2;
if(m <= 5) return n + 2;
return 0;
}

long xorSequence(long l, long r) {
return helper(r) ^ helper(l - 1);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/12/PS/HackerRank/xor-se/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.