89. Gray Code

195 篇文章 0 订阅
问题描述

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.
题目链接:


思路分析

灰码(我也不知道是啥玩意)是一个二进制系统,它其中的所有连续的数,转化成二进制之后只有一位数字是不同的。给一个数字n,返回n位二进制数的灰码。

灰码的个数一定是 2n 个的,而且一定是全部都有的,所以我们首先声明一个那么大的空间,可以是pow(2, n),也可以直接将1向左移动n位。这道题目也是主要使用了移位的操作的。

然后循环遍历存储结果,将i右移1位然后和它自己异或的结果肯定和自己只有一位是不同的。完美解决问题。

代码
class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> res(1<<n);
        for (int i = 0; i < (1<<n); i++){
            res[i] = i ^ (i>>1);
        }
        return res;
    }
};

时间复杂度: O(mn)
空间复杂度: O(1)


反思

以下是 C++ ISO 规范 (INCITS/ISO/IEC 14882-2011[2012]) 5.8.2 和 5.8.3 两节中对移位运算符的说明。

E1 << E2 的值是 E1 向左移动 E2 位的结果,空出的位用零填充。 如果 E1 属于无符号类型,则结果的值为 E1 × 2E2,约减的模一大于结果类型可表示的最大值。 否则,如果 E1 属于有符号类型且为非负值,E1 × 2E2 可由结果类型的相应无符号类型表示,则该值转换为结果类型后即为得到的值;否则,该行为是不确定的。

E1 >> E2 的值是 E1 向右移动 E2 位的结果。 如果 E1 属于无符号类型或 E1 属于有符号类型且为非负值,则结果值为 E1/2E2 之商的整数部分。 如果 E1 属于有符号类型且为负值,则结果值由实现决定。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值