2016-11-16 77 views
-4

我从hackerearth.com使用python(V2)XOR逻辑在python

陈述问题解决了这个问题:Xor is Mad

我的代码是:

tests = int(raw_input()) 
for i in range(tests): 
x = int(raw_input()) 
c = 0 
b = x 
a = x-1 
while a > 0: 
    xor = a^b 
    summ = b + a 
    # print "XOr : ",xor 
    # print "Sum : ",summ,"\n--------" 
    if xor == summ: 
     c += 1 
     a -= 1 
    elif a > 0: 
     a -= 1 
print c 

但我已经超过时间问题对于输入:输入#5到#9

有人可以用不同的方式解决这个问题,以管理在1秒内执行的测试。

+0

你能不能给我们一些测试的?你的代码输入缓慢了些什么? –

+0

你好@PatrickHaugh,你可以在黑客那里提交这个答案,并检查输入#5到#9 ..实际上他们提供的测试文件包含10K-100K行。你可以请一些时间来这个。谢谢 –

回答

1

诀窍是认识到你不必测试所有a高达x。对于a^x == a+x,然后a&x == 0。因此,我们统计的零的数量的x位串,然后出来的答案是2**count -1

test = int(input()) 
for _ in range(test): 
    x = int(input()) 
    print(2**bin(x)[2:].count('0') -1) 
+0

非常感谢帕特里克这个逻辑。 –