vYou are given an integer array pref of size n. Find and return the array arr of size n that satisfies:
- pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].
Note that ^ denotes the bitwise-xor operation.
It can be proven that the answer is unique.
Example 1:
Input: pref = [5,2,0,3,1]
Output: [5,7,2,3,2]
Explanation: From the array [5,7,2,3,2] we have the following:
- pref[0] = 5.
- pref[1] = 5 ^ 7 = 2.
- pref[2] = 5 ^ 7 ^ 2 = 0.
- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3.
- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1.
Example 2:
Input: pref = [13]
Output: [13]
Explanation: We have pref[0] = arr[0] = 13.
출처 : https://leetcode.com/problems/find-the-original-array-of-prefix-xor/description/
풀이
function findArray(pref: number[]): number[] {
let arr: number[] = [pref[0]]
for (let i = 1; i < pref.length; i++) {
arr.push(pref[i] ^ pref[i - 1]);
}
return arr;
};
XOR 연산 설명
XOR 연산(^)은 두 비트가 서로 다를 때 1을 반환하고, 같을 때 0을 반환하는 비트 연산
예를 들어:
- 0 ^ 0 = 0
- 0 ^ 1 = 1
- 1 ^ 0 = 1
- 1 ^ 1 = 0
a = 1010
b = 1100
-------------
a: 1 0 1 0
b: 1 1 0 0
-----------
0 1 1 0
예제
입력 배열 pref가 [5, 2, 0, 3, 1]인 경우
- arr의 첫 번째 요소는 pref의 첫 번째 요소로 초기화
- arr = [5]
- 두 번째 요소부터 XOR 연산을 통해 arr에 추가
- arr[1] = pref[1] ^ pref[0] = 2 ^ 5 = 7 (2와 5의 XOR 연산 결과)
- arr[2] = pref[2] ^ pref[1] = 0 ^ 2 = 2 (0과 2의 XOR 연산 결과)
- arr[3] = pref[3] ^ pref[2] = 3 ^ 0 = 3 (3과 0의 XOR 연산 결과)
- arr[4] = pref[4] ^ pref[3] = 1 ^ 3 = 2 (1과 3의 XOR 연산 결과)
- 최종 arr 배열은 [5, 7, 2, 3, 2]
'LeetCode' 카테고리의 다른 글
| 1156. Swap For Longest Repeated Character Substring / TypeScript (1) | 2024.07.19 |
|---|---|
| 1249. Minimum Remove to Make Valid Parentheses / TypeScript (1) | 2024.07.18 |
| 3179. Find the N-th Value After K Seconds / TypeScript (0) | 2024.07.15 |
| 1834. Single-Threaded CPU / TypeScript (0) | 2024.07.02 |
| 640. Solve the Equation / TypeScript (1) | 2024.07.01 |