There is a hidden integer array arr that consists of n non-negative integers.
It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3].
You are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0].
Return the original arrayarr. It can be proved that the answer exists and is unique.
Given the first element and the encoded array, we can reconstruct the original array by reversing the XOR operation. Since encoded[i] = arr[i] XOR arr[i+1], we can get arr[i+1] = encoded[i] XOR arr[i].
classSolution {
publicint[]decode(int[] encoded, int first) {
int n = encoded.length;
int[] ans =newint[n + 1];
ans[0]= first;
for (int i = 0; i < n; i++) {
ans[i + 1]= ans[i]^ encoded[i];
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
fundecode(encoded: IntArray, first: Int): IntArray {
val n = encoded.size
val ans = IntArray(n + 1)
ans[0] = first
for (i in0 until n) {
ans[i + 1] = ans[i] xor encoded[i]
}
return ans
}
}
1
2
3
4
5
6
7
classSolution:
defdecode(self, encoded: list[int], first: int) -> list[int]:
n: int = len(encoded)
ans: list[int] = [first]
for e in encoded:
ans.append(ans[-1] ^ e)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfndecode(encoded: Vec<i32>, first: i32) -> Vec<i32> {
let n = encoded.len();
letmut ans = Vec::with_capacity(n +1);
ans.push(first);
for&e in&encoded {
let last =*ans.last().unwrap();
ans.push(last ^ e);
}
ans
}
}