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

后端 未结 9 1114
醉梦人生
醉梦人生 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 19:03

    I've had to solve this question in an interview as well. One of the conditions for the two values to be a gray code sequence is that their values only differ by 1 bit. Here is a solution to this problem:

    def isGrayCode(num1, num2):
        differences = 0
        while (num1 > 0 or num2 > 0):
            if ((num1 & 1) != (num2 & 1)):
                differences++
            num1 >>= 1
            num2 >>= 1
        return differences == 1
    

提交回复
热议问题