Changing Bits Discussions | Algorithms | HackerRank
  • + 2 comments

    Python 3 approach passes all testcases. Finally!!! I shouldn't have converted the numbers to binary strings to get the bit. I didn't use segment tree, just bit manipulation is enough. I would like to ask experts in Python what was the time taken for their Testcases and how can I further reduce it? Also, let me know any other helpful advice if possible.

    Time taken for test cases:

    '''
     0. ~0s
     1. ~4.31s
     2. ~0.51s
     3. ~0.4s
     4. ~4.4s
     5. ~4.29s
     6. ~0.03s
     7. ~0.78s
     8. ~0.28s
     9. ~0.8s
    10. ~0.43s
    '''
    
    def setbit(val, i, bit):
    
        num = 1 << i
    
        if bit:
            return val | num
    
        return val & ~num
    
    n, q = map(int, input().strip().split(' '))
    a = int(input().strip(),2)
    b = int(input().strip(),2)
    out = ''
    
    for i in range(q):
    
        cmd = input().strip().split(' ')
        inx = int(cmd[1])
        cmd.append(7)
        bit = int(cmd[2])
    
        if cmd[0] =='set_a':
    
            a = setbit(a, inx, bit)
    
        elif cmd[0] =='set_b':
    
            b = setbit(b, inx, bit)
    
        else:
    
            c = a+b
            cbit = int (bool (c & (1<<inx)))
            out += str(cbit)
    
    print (out)