We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Simple python solution that follows the methodology described by the editorial
Note: My initial implementation used masks to read and set the bits, but I found this wasn't fast enough for the last 3 tests. Converting to an array and accessing the bits by index proved to be much faster.
#!/bin/python3importmathimportosimportrandomimportreimportsys## Complete the 'aOrB' function below.## The function accepts following parameters:# 1. INTEGER k# 2. STRING a# 3. STRING b# 4. STRING c#defaOrB(k,a,b,c):# Write your code herea_arr=[int(i)foriinbin(int(a,16))[2:]]b_arr=[int(i)foriinbin(int(b,16))[2:]]c_arr=[int(i)foriinbin(int(c,16))[2:]]a_mod=4-len(a_arr)%4b_mod=4-len(b_arr)%4c_mod=4-len(c_arr)%4ifa_mod<4:a_arr[:0]=[0]*a_modifb_mod<4:b_arr[:0]=[0]*b_modifc_mod<4:c_arr[:0]=[0]*c_modswap=0foriinrange(len(c_arr)):ifc_arr[i]:ifnota_arr[i]andnotb_arr[i]:b_arr[i]=1swap+=1else:ifa_arr[i]:a_arr[i]=0swap+=1ifb_arr[i]:b_arr[i]=0swap+=1ifswap>k:print(-1)returnleft_over=k-swapforiinrange(len(c_arr)):ifleft_over==0:breakifa_arr[i]:ifb_arr[i]:a_arr[i]=0left_over-=1elifleft_over>=2:a_arr[i]=0b_arr[i]=1left_over-=2a=int(''.join([str(i)foriina_arr]),2)b=int(''.join([str(i)foriinb_arr]),2)print(hex(a)[2:].upper())print(hex(b)[2:].upper())if__name__=='__main__':q=int(input().strip())forq_itrinrange(q):k=int(input().strip())a=input()b=input()c=input()aOrB(k,a,b,c)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
A or B
You are viewing a single comment's thread. Return to all comments →
Simple python solution that follows the methodology described by the editorial
Note: My initial implementation used masks to read and set the bits, but I found this wasn't fast enough for the last 3 tests. Converting to an array and accessing the bits by index proved to be much faster.