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

后端 未结 9 1096
醉梦人生
醉梦人生 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:13
    public int checkConsecutive2(int b1, int b2){
        int x =  (b1 ^ b2);
    
        if((x & (x - 1)) !=0){
          return 0;
        }else{
          return 1;
        }
    
    }
    
    0 讨论(0)
  • 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));
        }
    }
    
    0 讨论(0)
  • 2021-02-04 19:21

    An obvious answer, but it works. Convert each gray code into its respective Binary form, subtract the two. If you answer is a binary equivalent of +1 or -1 then the two gray codes are adjacent.

    This seems like an over kill, but when you're siting in an interview and don't know the correct method, this works. Also to optimize, one can check the single bit difference filter, so we don't waste time converting and subtracting numbers that we know for sure aren't adjacent.

    0 讨论(0)
提交回复
热议问题