Skip to content

Commit c3153b1

Browse files
authored
Create xor-operation-in-an-array.py
1 parent b992afb commit c3153b1

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Python/xor-operation-in-an-array.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time: O(1)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def xorOperation(self, n, start):
6+
"""
7+
:type n: int
8+
:type start: int
9+
:rtype: int
10+
"""
11+
def xorNums(n, start):
12+
def xorNumsBeginEven(n, start):
13+
assert(start%2 == 0)
14+
# 2*i ^ (2*i+1) = 1
15+
return ((n//2)%2)^((start+n-1) if (n%2) else 0)
16+
17+
return start^xorNumsBeginEven(n-1, start+1) if start%2 else xorNumsBeginEven(n, start)
18+
19+
return int(n%2 and start%2) + 2*xorNums(n, start//2)
20+
21+
22+
# Time: O(n)
23+
# Space: O(1)
24+
class Solution2(object):
25+
def xorOperation(self, n, start):
26+
"""
27+
:type n: int
28+
:type start: int
29+
:rtype: int
30+
"""
31+
return reduce(operator.xor, (i for i in xrange(start, start+2*n, 2)))

0 commit comments

Comments
 (0)