[leetcode](Gray Code 格雷码 C语言实现)

本文介绍了格雷码的概念,它是一种二进制码,相邻两个值只有一位不同。针对非负整数n,给出了如何生成n位格雷码序列的方法。以n=2为例,序列应为[0,1,3,2]。虽然格雷码序列不唯一,但这里提供了一种C语言实现的转换代码示例。" 119182287,11203486,SQL查询技巧:exists、排序与全字段查询,"['数据库', 'SQL查询', '数据筛选', '数据排序']

Gray Code
The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

00 - 0
01 - 1
11 - 3
10 - 2
Note:
For a given n, a gray code sequence is not uniquely defined.

For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
gary code(格雷码):参照百度百科,
公式表示:

(G:格雷码,B:二进制码)
例如:二进制码0101,为4位数,所以其所转为之格雷码也必为4位数,因此可取转成之二进位码第五位为0,即0 b3 b2 b1 b0。
0 xor 0=0,所以g3=0
0 xor 1=1,所以g2=1
1 xor 0=1,所以g1=1
0 xor 1=1,所以g0=1
因此所转换为之格雷码为0111
实现C代码如下:

/**解题思路:gray code 满足Gi = Bi^B(i+1),把二进制码转换为gray码:即从右到左,倒数第一位与倒数第二位进行异或,得到gray码的倒数第一位,依次比较下去,并把二进制码的第一位原样输出作为gray码的第一位。
 * 例如:
 *              二进制码        gray code
 *              0000    ->        0000
 *              0001    ->        0001
 *              0010    ->        0011
 *              0011    ->        0010
 *              0100    ->        0110
 *              0101    ->        0111
 *              0110    ->        0101
 *              0111    ->        0100
 *              1000    ->        1100
 *              1001    ->        1101
 *              1010    ->        1111
 *              1011    ->        1110
 *              1100    ->        1010
 *              1101    ->        1011
 *              1110    ->        1001
 *              1111    ->        1000
 * Definition for an integer array.
 * struct IntArray {
 *     int* elements;
 *     int size;
 * };
 */
struct IntArray* grayCode(int n) {
    struct IntArray *p;
    int i,temp;
    p = (struct IntArray *)malloc(sizeof(struct IntArray));
    p->size = 1;
    for(i=0;i<n;i++){
        p->size *= 2;
    }
    p->elements = (int *)malloc(p->size*sizeof(int));
    memset(p->elements,0,sizeof(p->elements));
    for(i=0;i<p->size;i++){
        temp = i;
        p->elements[i] = (i>>1)^temp;//实现异或
    }
    return p;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值