Skip to content

Commit 3e9f11e

Browse files
check
1 parent cd110ab commit 3e9f11e

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Diff for: bit_manipulation/binary_xor_operator_new.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
2+
3+
4+
def binary_xor(a: int, b: int) -> str:
5+
"""
6+
Take in 2 integers, convert them to binary,
7+
return a binary number that is the
8+
result of a binary xor operation on the integers provided.
9+
10+
>>> binary_xor(25, 32)
11+
'0b111001'
12+
>>> binary_xor(37, 50)
13+
'0b010111'
14+
>>> binary_xor(21, 30)
15+
'0b01011'
16+
>>> binary_xor(58, 73)
17+
'0b1110011'
18+
>>> binary_xor(0, 255)
19+
'0b11111111'
20+
>>> binary_xor(256, 256)
21+
'0b000000000'
22+
>>> binary_xor(0, -1)
23+
Traceback (most recent call last):
24+
...
25+
ValueError: the value of both input must be positive
26+
>>> binary_xor(0, 1.1)
27+
Traceback (most recent call last):
28+
...
29+
TypeError: 'float' object cannot be interpreted as an integer
30+
>>> binary_xor("0", "1")
31+
Traceback (most recent call last):
32+
...
33+
TypeError: '<' not supported between instances of 'str' and 'int'
34+
"""
35+
if a < 0 or b < 0:
36+
raise ValueError("the value of both input must be positive")
37+
38+
a_binary = str(bin(a))[2:] # remove the leading "0b"
39+
b_binary = str(bin(b))[2:] # remove the leading "0b"
40+
41+
max_len = max(len(a_binary), len(b_binary))
42+
43+
return "0b" + "".join(
44+
str(int(char_a != char_b))
45+
for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len))
46+
)
47+
48+
49+
if __name__ == "__main__":
50+
import doctest
51+
52+
doctest.testmod()

0 commit comments

Comments
 (0)