def add(x,y):
c = 0
while(y>0):
c+=1
u = x ^ y
v = x and y
x = u
y = v*2
return x
for _ in range(int(input())):
a = input()
b = input()
c =0
d =0
for i in a:
c=c*2+int(i)
for i in b:
d=d*2+int(i)
print(c,d)
print(c^d)
print(add(c,d))
First of all the solution which you are giving for the problem BINADD by first finding the decimal equivalent of the given number and then executing the steps, as it is defined in the problem statement because python support big-integers will not pass the last test-case, and will give you TLE.
As per the posted source-code, you don’t need to convert the given binary number into decimal explicitly because in python you can directly find the decimal equivalent usng int() function.
a = int("0b" + intput().rstrip(), base = 2)
b = int("0b" + input().rstrip(), base = 2)
Refer to the following source code:
def binary_addition(a,b):
loop_count = 0
while b != 0:
loop_count += 1
x = a ^ b
y = a & b
a = x
b = y << 1
return loop_count
def main():
for t in range(int(input().rstrip()):
a = int('0b' + input().rstrip(),base = 2)
b = int('0b' + input().rstrip(),base = 2)
if not b:
print("0")
elif not a:
print("1")
elif a == b:
print("2")
else:
print(binary_addition(a,b))
if __name__ == "__main__":
main()
Tip: Whenever you are finding the decimal equivalent of a binary number you can use the following algorithm:
binary_string = input().rstrip()
decimal_equivalent = 0
for bit in binary_string:
decimal_equivalent = 2 * decimal_equivalent + int(bit)
print(decimal_equivalent)
If you want to solve the problem under the given time-limit use the concept of Largest Carry Sequence as explained in this post.
Thanks for reading.
Peace