Application of XOR in algorithm

Application of XOR in algorithm

The XOR (Exclusive OR) operation returns true (1) if one or the other (but not both) is 1. Otherwise, it returns false (0).

Properties of XOR

  1. Identity ?????????????????????? a ^ 0 = a
  2. Self-Inverse ??????????????? a ^ a = 0
  3. Associative ??????????????? ( a ^ b ) ^ c = a ^ ( b ^ c )
  4. Commutative ???????????? a ^ b = b ^ a
  5. Toggled bit value ?????? a ^ (1111)


Application of XOR

1) Swapping without variable

a = a ^ b????????? # XOR the bits and store the result in a????????

b = a ^ b ???????? # XOR the result with b and store it in b

a = a ^ b ???????? # XOR the result with a and store it in a

now a and b are swapped

2) Finding the single missing element in a sequence of number from 1 to n.

a = XOR of numbers from 1 …n

b = XOR of numbers from 1 to n, excluding one number c, where c ranges from 1 to n.

c = a ^ b

3) Finding a number in a sequence of numbers where only one number is repeated an odd number of times.

Example - 1,2,2,1,3,4,5,5,4 XOR of all numbers will return 3 as XORing even times a number return 0 and XORing a number with 0 return the number

4) Self-Inverse property is often utilized in algorithms where you need to cancel out pairs of identical elements.

plain text ^ key = cipher text

cipher text ^ key = plain text

?

aryan .

UBER (e) || JAVA(Springboot-Microservices) & ANGULAR

1 年

These applications of XOR are really good ?? !!

Swastik Dey

IoT and VLSI Designs Engineer

1 年

Shreya Das, we could have used XOR operation to swap the variables instead of performing the Arithmetic Operations. ??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了