Bit Operation Series 2-leetcode136 (c ++ / python)

topic

Thinking

This question can be used XOR operation!

Shajiao XOR? (Source 2)

XOR operation has the following characteristics

  • Any number 0 and the exclusive OR of itself: a ^ 0 = a
  • Any number with their XOR result is 0: a ^ a = 0
  • XOR commutative and associative: A B A = (A A) B = B

This question, a number appears only once, the rest have occurred twice, the above-described characteristics, can be solved efficiently.

answer

C++:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
       int ans=0;
       for (auto i :nums)
       {
           ans^=i;
       }
        return ans;
    }
};

Python:

from functools import *
class Solution(object):
    def singleNumber(self, nums):
        return reduce(lambda x,y:x^y,nums)

reference

1.https://leetcode-cn.com/problems/single-number/

2.https://mp.weixin.qq.com/s/YasCeiVzUlS-pMBa0nUpsg

Guess you like

Origin www.cnblogs.com/depth-perception/p/12600404.html