How to find if two numbers are consecutive numbers in gray code sequence

后端 未结 9 1197
醉梦人生
醉梦人生 2021-02-04 18:44

I am trying to come up with a solution to the problem that given two numbers, find if they are the consecutive numbers in the gray code sequence i.e., if they are gray code neig

9条回答
  •  自闭症患者
    2021-02-04 18:55

    Assumptions: Inputs a and b are grey code sequences in binary reflected gray code. i.e a's and b's bit encoding is binary gray code representations.

    #convert from greycode bits into regular binary bits
    def gTob(num): #num is binary graycode 
        mask = num >> 1
        while mask!=0:
            num = num^mask
            mask >>= 1
        return num; #num is converted 
    
    #check if a and b are consecutive gray code encodings
    def areGrayNeighbors(a,b):
        return abs(gTob(a) - gTob(b)) == 1
    

    Few Test cases:

    • areGrayNeighbors(9,11) --> True (since (1001, 1011) differ in only one bit and are consecutive numbers in decimal representation)
    • areGrayNeighbors(9,10) --> False
    • areGrayNeighbors(14,10) --> True

    References: method gTob() used above is from rodrigo in this post The neighbors in Gray code

提交回复
热议问题