https://leetcode.com/problems/single-number/

 

Single Number - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


풀이 과정

배열에서 딱 한번만 나오는 원소를 출력하는 문제이다.

 

비트 연산중에 XOR 연산은 비트가 같으면 0, 다르면 1을 출력한다. 0을 저장하고 있는 변수에 배열의 모든 원소들을 XOR 연산을 하면 2번씩 나온 원소들은 bit 연산중 0으로 바뀌고 1번 나온 원소의 bit만 남게될 것이다.


소스 코드

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        answer = 0
        for num in nums:
            answer ^= num
        return answer

 

+ Recent posts