[코테 풀이] Single Number

시내·2024년 6월 6일

Q_136) Single Number

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

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.

class Solution {
    public int singleNumber(int[] nums) {
         int res = 0;
        for (int i = 0; i < nums.length; i++) {
            res = res ^ nums[i];
        }
        return res;
    }
}

🙈 풀이 참조한 문제

  • xor 연산 이해하기
  • 0⊕0=0
    1⊕1=0
    0⊕1=1
    1⊕0=1
    즉, 두 연산자가 같으면 0, 다르면 1

이걸 어떻게 생각해내지..🥹

profile
contact 📨 ksw08215@gmail.com

0개의 댓글