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

后端 未结 9 1104
醉梦人生
醉梦人生 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条回答
  •  梦毁少年i
    2021-02-04 19:15

    You can check if two numbers differ by one bit or not as follows. In this method, difference in the length of binary numbers are taken care of. Eg, the output for 11 (1011) and 3 (11) will be returned as true. Also, this does not solve the second criteria for Gray code adjacency. But if you only want to check if the numbers differ by one bit, the code below will help.

    class Graycode{
        public static boolean graycheck(int one, int two){
            int differences = 0;
            while (one > 0 || two > 0){
                // Checking if the rightmost bit is same
                if ((one & 1) != (two & 1)){
                    differences++;
                }
                one >>= 1;
                two >>= 1;
            }
            return differences == 1;
        }
        public static void main(String[] args){
            int one = Integer.parseInt(args[0]);
            int two = Integer.parseInt(args[1]);
            System.out.println(graycheck(one,two));
        }
    }
    

提交回复
热议问题