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

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

    If you just want to check if the input numbers differ by just one bit:

    public boolean checkIfDifferByOneBit(int a, int b){
        int diff = 0;
        while(a > 0 && b > 0){
            if(a & 1 != b & 1)
                diff++;
            a = a >> 1;
            b = b >> 1;
        }
        if (a > 0 || b > 0) // a correction in the solution provided by David Jones
            return diff == 0 // In the case when a or b become zero before the other
        return diff == 1;
    }
    

提交回复
热议问题