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所有字符异或,结果为单独的字母。

猜你喜欢

转载自blog.csdn.net/ZHOUBEISI/article/details/79450519