Help me in solving SHKNUM problem

My issue

expected output is 2
but i am getting 8

My code

# cook your dish here
for i in range(int(input())):
    n=int(input())
    if n==1:print(2)
    elif n==2:print(1)
    else:
        a=n
        x=''
        x1,c='',0
        while n!=0:
            x=str(n%2)+x
            n=n//2
        if x.count('1')==2:print(0)
        elif x.count('1')==1:print(1)
        else:
            j,c=0,0
            while c<2:
                if x[j]=='1':c+=1
                j+=1
            if j==2:
                x1=2**(len(x))+1
                x2=2*(len(x)-1)+2*(len(x)-2)
            else:
                x1=2*(len(x)-1)+2*(len(x)-(j))
                x2=2*(len(x)-1)+2*(len(x)-(j-1))
            print(min(abs(a-x1),abs(a-x2)))

Learning course: Kalasalingam Academy of Research and Education
Problem Link: CodeChef: Practical coding for everyone