zoukankan      html  css  js  c++  java
  • [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 };
  • 相关阅读:
    springboot之session、cookie
    Springboot的异步线程池
    spring自带的定时任务功能@EnableScheduling
    SpringBoot+SpringCloud实现登录用户信息在微服务之间的传递
    sss
    sss
    sss
    sss
    sss
    sss
  • 原文地址:https://www.cnblogs.com/skycore/p/4881082.html
Copyright © 2011-2022 走看看