zoukankan      html  css  js  c++  java
  • [leedcode 89] 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.

    public class Solution {
        public List<Integer> grayCode(int n) {
           //自然数(二进制表示)转化为格雷码的公式是:i>>1^i
           //例如:Binary Code :1011 要转换成Gray Code 
           //(1011 >> 1)^1011 = 1110
            int size=1<<n;//先求出二进制一共的个数
            List<Integer> res=new ArrayList<Integer>();
            for(int i=0;i<size;i++){
                res.add(i>>1^i);
            }
            return res;
        }
            /*格雷码的规律是 将格雷码看成是上下两部分 n=1 
    
            上 0  下 1
    
            当n=2
    
            上为n=1时的格雷码 
    
            下为n=1时的格雷码的倒序再加上最前面的1*/
    }
  • 相关阅读:
    内存分配问题
    C++ assert 的一点说明
    强大的stringstream
    C++中随机数
    C++ 中new
    C++ 中string 详解 转载自 博客园
    未命名名字空间
    使用ifstream和getline读取文件内容[c++]
    6.bootstrap练习笔记-缩略图和list-group
    3.bootstrap练习笔记-媒体内容
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4650875.html
Copyright © 2011-2022 走看看