zoukankan      html  css  js  c++  java
  • 89. Gray Code java solutions

    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.

     1 public class Solution {
     2     public List<Integer> grayCode(int n) {
     3         List<Integer> ans = new ArrayList<Integer>();
     4         int len = (int)Math.pow(2,n);
     5         for(int i = 0; i< len ;i++){
     6             ans.add(i^(i>>1));// 按照数学公式的解法。G(N) = (B(n)/2) XOR B(n).
     7         }
     8         return ans;
     9     }
    10 }

    二进制数转格雷码

    (假设以二进制为0的值做为格雷码的0)

    G:格雷码 B:二进制码

    G(N) = (B(n)/2) XOR B(n).

    以三位为例:

    000^000-->000

    001^000-->001

    010^001-->011

    011^001-->010

    100^010-->110

    101^010-->111

    110^011-->101

    111^011-->100

    解法二: 可用递归。以后在总结。

    参考帖子:

    http://blog.csdn.net/makuiyu/article/details/44926463

    http://www.cnblogs.com/peihao/p/5269151.html (第二个帖子描述的还是不够清晰一些)

  • 相关阅读:
    python
    HTTP和HTTPS协议,详解
    常用加密算法之非对称加密算法
    Docker容器数据卷-Volume详解
    使用nsenter进入docker容器后端报错 mesg: ttyname failed: No such file or directory
    Docker 查看容器 IP 地址
    Docker容器数据卷volumes-from
    Docker 进入容器的4种方法
    Jmeter之Bean shell使用(二)
    Jmeter之Bean shell使用(一)
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5619709.html
Copyright © 2011-2022 走看看