89. Gray Code (Bit)
2024-08-25 09:05:03
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.
思路:
二进制-->格雷码:如果二进制码字的第i位和i+1位相同,则对应的格雷码的第i位为0,否则为1。最高为之前可以看作还有一位0,即最高位是和0异或。
*格雷码-->二进制:最左边一位不变,从左边第二位起,将每位与左边一位解码后的值异或,作为该位解码后的值。
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> result;
int size = << n;
for (int i =; i< size; i++)
{
result.push_back(getGrayCode(i));
}
return result;
}
int getGrayCode(int binary)
{
return ((binary >> )^binary);
}
};
最新文章
- 如何在 IIS 上搭建 mercurial server
- Understanding Convolutions
- Node.js之Promise
- 教你怎么安装MongoDB
- python_ftplib实现通过FTP下载文件
- C语言面试题(嵌入式开发方向,附答案及点评)
- ThinkPHP 中使用 PHPMailer 发送邮件 支持163和QQ邮箱等
- c语言结构体1之定义
- dotnet new 命令使用模板
- c#导入excel 绑定数据 repeat为例子
- 安装python caffe过程中遇到的一些问题以及对应的解决方案
- Python3基础-特别函数(map filter partial reduces sorted)实例学习
- nodejs(二)浏览器与服务器连接初探
- list集合排序
- Angular2入门:TypeScript的函数 - 剩余参数和箭头函数
- 错误票据|2013年蓝桥杯B组题解析第七题-fishers
- arcengine直连sde
- Poj 题目分类
- LintCode - Copy List with Random Pointer
- 数据库中的B树和B+树
热门文章
- MySQL Binlog三种格式介绍及分析
- Missing Number @leetcode
- 使用oracle导出的dmp文件(包含表结构还是表数据?)
- 本地管理表空间和字典管理表空间的特点,ASSM有什么特点
- PHP mysqli_free_result()与mysqli_fetch_array()函数
- bash下. : () {} [] [[]] (())的解释
- 开发组件:REST API
- python应用之爬虫实战2 请求库与解析库
- Visual Studio自动添加头部注释
- 0_Simple__vectorAdd + 0_Simple__vectorAdd_nvrtc + 0_Simple__vectorAddDrv