2016-11-16 74 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

非常感謝帕特里克這個邏輯。 –