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

后端 未结 9 1111
醉梦人生
醉梦人生 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:01

    If two numbers are in gray code sequence, they differ by one binary digit. i.e the exclusive OR on the two numbers returns a power of 2. So, find XOR and check if the result is a power of two.

    This solution works well for the all the test cases written by CodeKaichu above. I would love to know if it fails in any cases.

    public boolean grayCheck(int x, int y) {
           int z = x^y;
           return (z&z-1)==0;
    }
    

提交回复
热议问题