XOR Operation Intuition

前端 未结 7 1655
滥情空心
滥情空心 2020-12-24 07:12

I recently came across this question on Leetcode and figured out a solution that I need some clarification with:

Given an array of integers, every ele

7条回答
  •  旧时难觅i
    2020-12-24 07:23

    XOR is always defined in terms of binary digits (or some equivalent notions, like true or false statements). There is no special XOR for integers other than the XORing of corresponding bits of their binary representations.

    Let A and B be two boolean variables, and let XOR be a boolean function that takes two boolean variables.
    A⊕B = 1 if either (A = 0 and B = 1) or (A = 1 and B = 0) (i.e. they are different),
    A⊕B=0 if either (A = 0 and B = 0) or (A = 1 and B = 1). (i.e they are same)

    Thus taking your question into consideration since out of given n elements of the vector ,every element appears twice except one element,the idea is that the binary representation of the duplicate numbers would be same thus there XOR result would nullify each other as 1⊕1 =0 and 0⊕0= 0.

    For A=5 ,its binary representation is 101,so A⊕A = (101)⊕(101) = 000 which is the decimal representation is 0.

    REMEMBER IT DOES NOT MATTER IN WHICH ORDER THE NUMBERS APPEAR AFTER EACH OTHER BECAUSE ((A⊕B)⊕C) = (A⊕(B⊕C)) . Eventually what you get at the end after XORING every number is the number which occurs once .

    To answer your question regarding when you need to use XOR operations for solving a question, practice some BIT MANIPULATION question eventually you will be able to figure out.
    A hint: The question which asks to find one element which has unique property apart from rest, requires bit manipulation.
    Example: Given an array where every element occurs three times, except one element which occurs only once. Find the element that occurs once .

提交回复
热议问题