LeetCode 上的位运算的题目是算法最有意思的地方,我会接连好几篇博客都来写关于位运算的题目
(第136题的核心点在于异或操作,两个相同的整数异或操作之后得到的值是0,可以借助这个原理,将数组中的元素全部异或操作,得到的结果就是那个单个元素
Python 3代码)
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for i in nums:
a ^= i
return a
C# 代码
public class Solution {
public int SingleNumber(int[] nums)
{
int a = 0;
foreach(int i in nums)
a ^= i;
return a;
}
}