【Gray Code】cpp
题目:
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.
代码:
class Solution { public: vector<int> grayCode(int n) { std::vector<int> result; const size_t size = 1 << n; result.reserve(size); for (size_t i = 0; i < size; ++i) { result.push_back(i ^ ( i >> 1)); } return result; } };
Tips:
1. gray code与binary code之间的转换公式 “i 异或 (i右移1位)”
2. 这个代码鲁棒性比较强,即使n非常大(比如100000000)也只会返回0,不会crash
3. 另外调研了一下size_t的用法,后面再深入看看。
==========================================
第二次过Gray Code大概能想起来思路,但是记不牢了。看了一下之前的笔记,这道题考察的是位运算。
class Solution { public: vector<int> grayCode(int n) { vector<int> ret; const size_t N = 1 << n; ret.reserve(N); for ( int i=0; i<N; ++i ) ret.push_back(i ^ (i >> 1)); return ret; } };
这里的核心是算2的N次幂可以用1左移N位来计算;反之,除以2,或许也可以用右移1位来操作。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?