1. 程式人生 > >LeetCode-136. Single Number 389. Find the Difference

LeetCode-136. Single Number 389. Find the Difference

136. Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

Concept

  • If we take XOR of zero and some bit, it will return that bit
    • a 0 = a
  • If we take XOR of two same bits, it will return 0
    • a a = 0
  • a ba = (a a) b = 0b = b

So we can XOR all bits together to find the unique number.


class Solution {
    public int singleNumber(int[] nums) {
        int tmp=0;
        for(int num:nums){
            tmp^=num;
        }
        return tmp;
    }
}

389. Find the Difference

Given two strings s

 and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

Example:

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.
與136同理,將s與t所有字元異或,結果為單獨的字母。