I was presented with the following problem: given s and x, compute the number of solutions (a,b) that satisfy both 1) s = a + b, and 2) x = a XOR b. All quantities and operations are integer.
Example Inputs:
s = 10
x = 4
Output:
2
No modules can be imported.
I wrote the following answers which all took too long:
First:
def answer(s,x):
tally = 0
z = 0
while z <= s:
p = s - z
q = int(z ^ p)
if x == q:
tally += 1
z += 1
return tally
Second:
def answer(s,x):
spotlist, forwardlist = range(0,s+1)
backwardlist = range(s,-1,-1)
tally = 0
for spot in spotlist:
if x == forwardlist[spot] ^ backwardlist[spot]:
if s == forwardlist[spot] + backwardlist[spot]:
tally +=1
print tally
Third:
def answer(s,x):
tally = 0
z = 0
while z <= s:
q = int(z ^ (s - z))
if x == q:
tally += 1
else:
pass
z += 1
print tally
I think I'm missing something or iterating through the numbers before removing certain possible solutions.