LeetCode-136. Single Number 389. Find the Difference
阿新 • • 發佈:2018-12-25
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 ⊕b⊕a = (a ⊕ a) ⊕ b = 0⊕b = 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.