本文共 2271 字,大约阅读时间需要 7 分钟。
python xor
Question:
题:
John loves XOR. John's friends always ask him doubts related to XOR and he helps them to solve problems but he is busy because of his exams and asks you to help his friends. One of his friends wants your help with the following problem. Given an array of N numbers and a number K. The task is to insert the number in the given array such that the bitwise XOR of all the elements in the new array equals the give input K.
约翰爱XOR 。 John的朋友总是问他与XOR有关的疑问,他帮助他们解决问题,但由于考试而忙碌,并要求您帮助他的朋友。 他的一位朋友希望您解决以下问题。 给定N个数字和K个数组。 任务是将数字插入给定数组,以使新数组中所有元素的按位XOR等于给定输入K。
Input:
输入:
The first line of input contains an integer T denoting the numbers of test cases.
输入的第一行包含一个整数T,表示测试用例的数量。
The first line of each test case consists of 2 integers denoting N and K. The second line of each test case consists of N-space integers denoting the array.
每个测试用例的第一行包含2个表示N和K的整数。 每个测试用例的第二行包含N个表示数组的整数。
1 5 10 1 2 3 4 5
Output:
输出:
For each test case print the number by inserting which the XOR of all the elements in the array becomes equal to K.
对于每个测试用例,通过插入数组中所有元素的XOR等于K来打印数字。
Explanation: 1^2^3^4^5^11 = 10 Output: 11
Constraints:
限制条件:
1 <= T <100 1
To solve this question, we are using Python3.
为了解决这个问题,我们使用Python3。
In python, bitwise operators are used to perform the bitwise operation on integers. Firstly the integers are converted into binary digit and then bit by bit operation is performed and the result is returned in the decimal format.
在python中,按位运算符用于对整数执行按位运算。 首先,将整数转换为二进制数字,然后进行逐位操作,结果以十进制格式返回。
XOR operation table,
XOR运算表,
Operation | Result |
---|---|
0^0 | 0 |
0^1 | 1 |
1^0 | 0 |
1^1 | 0 |
操作方式 | 结果 |
---|---|
0 ^ 0 | 0 |
0 ^ 1 | 1个 |
1 ^ 0 | 0 |
1 ^ 1 | 0 |
Code:
码:
# Input test case (T)print("Input test case: ")t = int(input())while(t>0): t=t-1 # Input value of m and k print("Input value of m and k: ") m,k=list(map(int,input().split())) # Input array elements print("Input array elements: ") arr=list(map(int,input().split())) # Store first value res=arr[0] for i in range(1,m): # Perform the bitwise XOR operation # on elements in array res=res^arr[i] # print the result print("Result is: ") print(k^res)
Output
输出量
Input test case: 1Input value of m and k: 5 10Input array elements: 1 2 3 4 5Result is: 11
翻译自:
python xor
转载地址:http://jbtzd.baihongyu.com/