Gray Code

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;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今天的课程是很关键、很有趣、很深入,从理论层面到实修层面,更多地与自己在一起,尤其是星空冥想环节,从第一...
    王悦心Chris阅读 692评论 1 0
  • 1. OC 和 Swift 的不同 程序的入口 (@UIApplicationMain) 只有 .swif...
    freemanIT阅读 269评论 0 0
  • 第一次老公睡客厅的有感而发 今天第一次老公睡客厅,确切的说是第一次,忍着去没有像以前那样去把他给硬拽回来睡。不知道...
    会说话的布袋熊阅读 191评论 0 0