코딩테스트 풀이/JAVA
[LeetCode/Easy] 1486. XOR Operation in an Array
무지맘
2022. 12. 26. 13:04
1. Input
1) 정수 n
2) 정수 start
2. Output
1) 아래 규칙에 따라 만든 배열 nums의 요소들을 모두 bitwise XOR를 계산한 결과
// 규칙
- nums[i] = start + 2*i (i=0, 1, ..., n-1)
3. Constraint
1) 1 <= n <= 1000
2) 0 <= start <= 1000
3) n == nums.length
4. Example
Input: n = 5, start = 0 -> Output: 8
설명:
- 규칙에 따라 만든 nums = [0, 2, 4, 6, 8]
- 0 ^ 2 ^ 4 ^ 6 ^ 8 = 8이므로 8을 반환
// bitwise XOR: 비트별로 비교해서 두 비트가 다르면 1을, 같으면 0을 반환
- 0 ^ 2 -> 00 ^ 10 = 10 -> 2
- 0 ^ 2 ^ 4 -> 010 ^ 100 = 110 -> 6
- 0 ^ 2 ^ 4 ^ 6 -> 110 ^ 110 = 000 -> 0
- 0 ^ 2 ^ 4 ^ 6 ^ 8 -> 0000 ^ 1000 = 1000 -> 8
5. Code
1) 첫 코드(2022/06/05)
int result = start;
for(int i=1 ; i<n ; i++){
result ^= start + 2*i;
}
return result;