알고리즘
Single Number - XOR 연산자
avocado12
2021. 9. 27. 10:28
문제- leetcode
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
방법
2진수로 변환해 각 숫자가 같으면 0, 다르면 1로 나타내어지는 연산자이다.
예를 들어 배열 [4,1,2,1,2]가 있다고 할 때 중복되지 않는 숫자만 받고 싶다면
아래와 같이 사용할 수 있다.
const singleNumber = nums ⇒ { return nums.reduce((sum, current) ⇒ (sum^=current) }
각 숫자를 2진수로 표현하다면
4는 100, 1은 1, 2는 10,
배열에 있는 요소들을 더해보자 111 + 11 = 100
2진수 100을 10진수로 표현하면 4가 된다.
결국 중복되지 않은 값 하나만 얻을 수 있게된다.