Program to find xor of two numbers in python
Given two integers, find XOR of them without using the XOR operator, i.e., without using ^ in C/C++. Show Examples : Input: x = 1, y = 2 Output: 3 Input: x = 3, y = 5 Output: 6 A Simple Solution is to traverse all bits one by one. For every pair of bits, check if both are the same, set the corresponding bit like 0 in output, otherwise set it as 1. C++
C
Java
Python3
C#
Javascript
Time Complexity: O(num), where num is the number of bits in the maximum of the two numbers. Space Complexity: O(1) Thanks to Utkarsh Trivedi for suggesting this solution. Below is the implementation. C++
Java
Python3
C#
PHP
Javascript
Time Complexity: O(1) Space Complexity: O(1) Thanks to jitu_the_best for suggesting this solution. Alternate Solution : C++
Java
Python3
C#
Javascript
Time Complexity: O(1) Space Complexity: O(1) Another Solution: we can simply use one of the properties of the XOR bitwise operator i.e. a+b = a^b + 2*(a&b), with the help of this we can do the same for an operator variant also. C++14
Java
Python3
C#
Javascript
Time Complexity: O(1) i.e. simple calculation of arithmetic and bitwise operator. Auxiliary Space: O(1) Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. How do you find the XOR of two numbers in Python?Use the XOR operator ^ between two values to perform bitwise "exclusive or" on their binary representations. When used between two integers, the XOR operator returns an integer. When performing XOR on two booleans, True is treated as 1 , and False is treated as 0 . XOR between two booleans returns a boolean.
How do I get XOR 2 numbers?To find the XOR of two numbers, follow these instructions:. Convert the numbers into the binary representation.. Compare the corresponding bits of the two numbers.. If only one of the input bits is true (1), the output is true (1). Otherwise, the output is false (0).. How do you find the XOR of an element in Python?Suppose we have an integer n and another integer start. We have to create an array called nums where nums[i] = start + 2*i (i start from 0) and n is the size of nums. Then find the bitwise XOR of all elements of nums.
|