【Leetcode】Grey Code

来源:互联网 发布:大数据在银行的应用 编辑:程序博客网 时间:2024/06/05 06:04

【题目】

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 - 001 - 111 - 310 - 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 = 1

0
1

n=2

0 0
0 1
1 1
1 0

n=3

0 0 0
0 0 1
0 1 1
0 1 0
1 1 0
1 1 1
1 0 1
1 0 0

After growing some rows and cols of the table, you can tell how to build table n+1 from tablen, namely add 1 to each row of table n, reverse it and append on table n. The actual operation is easier since the output only requires a list(not a nested list), so adding bit 1 to a table row is just add 1<<(n-1) to the number that row represents.

【左移】

2<<1

2向左移一位

10--》100

2-》4

【代码】

public static ArrayList<Integer> gray(int n){    ArrayList<Integer> arr = new ArrayList<Integer>();    arr.add(0);    for(int i=0;i<n;i++){        int inc = 1<<i; //n是多少,就有多少位        for(int j=arr.size()-1;j>=0;j--){//倒过来相加            arr.add(arr.get(j)+inc);        }    }    return arr;}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 欢乐麻将老输怎么办 回不了家怎么办身份证 没注意闯红灯了怎么办 摩托车被套牌了怎么办? 发现员工偷钱怎么办 盗窃刑事拘留7天怎么办 盗窃抓不到人怎么办 发现宿舍被盗后怎么办(  ) 发现宿舍被盗后怎么办() 回收到赃物电瓶怎么办 不知情买了赃物怎么办 盗窃单位要报警怎么办 上网吸烟被逮住怎么办 有人在微信骂我怎么办 网吧抽烟被拍照怎么办 诈骗被拘留该怎么办 行政拘留人跑了怎么办 车牌号被偷了怎么办 当员工提出辞职怎么办 老员工提出辞职怎么办 家人进看守所了怎么办 被贷款中介诈骗怎么办 喝完酒吐难受怎么办 犯罪嫌疑人死在看守所怎么办 犯罪嫌疑人死不承认怎么办 高血压进了看守所怎么办 看守所里被欺负怎么办 老师上课迟到了怎么办 艾滋病看守所不收怎么办 没能力偿还债务怎么办 监狱病人的癌症怎么办 监狱的传染病人怎么办 犯人在监狱重病怎么办 亲戚被关拘留所怎么办 打麻将被拘留怎么办 轻伤检察院不批捕怎么办 吸毒人被拘留怎么办 法院拘留没去怎么办 羁押期限超过了怎么办 羁押期限已满怎么办 刑事拘留22天了怎么办