[Bit Operation-Simple] 1720. Array after Decoding XOR

[Title] The
unknown integer array arr consists of n non-negative integers.
After being encoded, it becomes another integer array encoded with length n-1, where encoded[i] = arr[i] XOR arr[i + 1]. For example, arr = [1,0,2,1] gets encoded = [1,2,3] after encoding.
Give you the encoded array encoded and the first element first (arr[0]) of the original array arr.
Please decode and return the original array arr. It can be proved that the answer exists and is unique.
[Example 1]
Input: encoded = [1,2,3], first = 1
Output: [1,0,2,1]
Explanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]
[Example 2]
Input: encoded = [6,2,7,3], first = 4
Output: [4,2 ,0,7,4]
[Prompt]
2 <= n <= 104
encoded.length == n-1
0 <= encoded[i] <= 105
0 <= first <= 105
[Code]
[Python]
Insert picture description here

class Solution:
    def decode(self, encoded: List[int], first: int) -> List[int]:
        rs=[first]
        for e in encoded:
            rs.append(rs[-1]^e)
        return rs

[Method 2]
Insert picture description here

class Solution:
    def decode(self, encoded: List[int], first: int) -> List[int]:
        encoded.insert(0,first)
        for index in range(1,len(encoded)):
            encoded[index]^=encoded[index-1]
        return encoded

Guess you like

Origin blog.csdn.net/kz_java/article/details/115091772