Use bit operations to find "numbers that only appear once"

"Number that only appears once"


Given an array of non-empty integers, except for an element that appears only once, every other element appears twice. Find the element that appears only once (use bitwise operations to solve this problem).
Such as [1,2,3,2,1], output 3

code show as below:

def solution():
    lst = list(int(n) for n in input('enter data:').split())
    temp = 0  # 初始temp设为0,用来与列表元素进行异或运算
    for i in range(len(lst)):
        temp = temp ^ lst[i]
    print(temp)

# 运行结果
# enter data:1 2 4 3 2 1 3
# 4

The XOR of two identical numbers is 0, and the XOR of 0 with a non-zero integer gets itself. The XOR operation can quickly solve this problem.

Perform exclusive OR operation from the input data in order, 0 and 1 are converted into binary to 0000,0001, 0^1=1,1 and 2 are XORed, and so on, the final result is only appearing The number at a time.

The XOR operation of a negative number must convert the original code into a complement code, and then convert the result ( complement code ) into the original code after the bitwise XOR operation . Such as -3^3, first convert it to binary, 1011,0011. The first bit is the sign bit. Since the complement of a positive number is the same as the original code, no conversion is required. The complement of 1011 is 1101 ( inverted and added to each bit ), and the result of the exclusive OR operation is 1110. Convert it to The final result of the original code is 1010, which is -2.

Guess you like

Origin blog.csdn.net/qq_43965708/article/details/108796274