[LeetCode]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.
解题思路:
该题目要求给出所有n比特格雷码序列,整数n的格雷码的数学公式:n ^ (n / 2)。
1 class Solution { 2 public: 3 vector<int> grayCode(int n) { 4 vector<int> result; 5 int size = 1 << n; 6 result.reserve(size); 7 for (int i = 0; i < size; ++i) { 8 result.push_back((i ^ (i >> 1))); 9 } 10 11 return result; 12 } 13 };
转载于:https://www.cnblogs.com/skycore/p/4881082.html
[LeetCode]Gray Code相关推荐
- LeetCode Gray Code(回溯法)
问题:gray code是一种二进制数字系统,两个连续的数只有一位不同.给出一个正整数n,n表示gray code的位数,输出gray code. 思路:使用回溯法.通过枚举0,1,2,3的gray ...
- LeetCode Gray Code 格雷码
题意:提供一个数字n,代表二进制的个数,那么就有2的n次方个可能性了,从0到2^n-1.将其转成格雷码,再直接将二进制的格雷码按二进制的读法变成整数,装在vector容器中返回,要有序(否则你直接将0 ...
- 【格雷码】LeetCode 89. Gray Code
LeetCode 89. Gray Code Solution1:我的答案 穷举法,比较笨 注意:牢记vector中find()函数的用法 class Solution { public:vector ...
- [LeetCode]89.Gray Code
[题目] The gray code is a binary numeral system where two successive values differ in only one bit. Gi ...
- LeetCode(89):格雷编码 Gray Code(Java)
2019.7.19 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新) 智力题,本题的关键在于搞清楚格雷编码的生成过程, G(i) = i ^ (i/2). 如 n = 3: G( ...
- leetcode笔记:Gray Code(2016腾讯软件开发笔试题)
2019独角兽企业重金招聘Python工程师标准>>> 一.题目描述 The gray code is a binary numeral system where two succe ...
- Gray Code LeetCode 89
题目:The gray code is a binary numeral system where two successive values differ in only one bit. Give ...
- 89. Gray Code - LeetCode
为什么80%的码农都做不了架构师?>>> Question 89. Gray Code Solution 思路: n = 0 0 n = 1 0 1 n = 2 00 01 1 ...
- Gray Code(格雷码) C++多方法实现
简介 在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同,则称这种编码为格雷码(Gray Code),另外由于最大数与最小数之间也仅一位数不同,即"首尾相连",因此又称循环 ...
最新文章
- Linux中netfilter模块编程实践
- oracle 创建带参数的视图
- CTF EasyStrcmp
- CentOS 网络设置修改
- 构建和测试JSF.next
- 武汉数字工程研究所计算机软件分数,武汉数字工程研究所2017考研成绩查询时间:2月16日...
- python打印目录结构_Python学习笔记(2)——遍历目录结构并打印
- 复制字符串 _strdup _wcsdup _mbsdup
- 【java与移动智能设备】高级用户组件
- 苹果mac能安装计算机题库吗,苹果电脑能装windows系统吗_苹果电脑安装windows系统的方法...
- 方正字体库大全(129款) 官方免费版​
- 网络存储学习之网络存储技术的发展现状及趋势
- iOS 中高级面试题(附答案)
- 项目技术管理经验总结
- 万物Linux皆可刷安卓,万物皆可Win,开发者成功在安卓手机刷入Win10系统
- Mezzanine 修改默认主页
- 东莞爱维EVER总线步进电机驱动器profinet连接实例
- 用C语言统计给定文本文件中汉字的个数。
- 空调系统的PUE值计算
- Android DatePicker 设置时间范围