Gray Code

作者: Wenyue_offer | 来源:发表于2017-09-13 13:58 被阅读0次

Problem:
Given two hexadecimal numbers find if they can be consecutive in gray code
For example: 10001000, 10001001
return 1
since they are successive in gray code

Example2: 10001000, 10011001
return -1
since they are not successive in gray code.

public class Solution {
    public static boolean isConsecutive(byte a, byte b)
    {
        byte c = (byte)(a ^ b);
        int count = 0;
        while(c != 0)
        {
            c &= (c - 1);
            count++;
        }
        return count == 1;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        byte a = 0x31, b = 0x33;
        System.out.println(isConsecutive(a, b));
    }
 
}

//term1和term2是题目给的两个BYTE
byte x = (byte)(term1 ^ term2);
int total = 0;
while(x != 0){
    x = (byte) (x & (x - 1));
    total++;
}
if(total == 1) return 1; else return 0;

相关文章

网友评论

      本文标题:Gray Code

      本文链接:https://www.haomeiwen.com/subject/jvgksxtx.html