zoukankan      html  css  js  c++  java
  • C++入门程序作业3

    /*

    输出n位数据的格雷码
    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.

    要求用向量做这道题,不能用公式
    */
    #include<math.h>
    #include <iostream>
    #include <algorithm>
    #include <string>
    #include <vector>
    using namespace std;

    int main()
    {
    vector<int>num0;//if n is determined, the number need to be transformed
    vector<int>num1;//from nomal number to 2 bit vector
    vector<int>num2;//to grey
    vector<int>num3;//to normal-binary
    vector<int>num4;//to align the grey
    int j=0;
    //according to n generate part of number;
    int n=4;

    for (int i=0;i<pow(2,n);i++)
    num0.push_back(i);

    cout<<"Given n = "<<n<<" , return [ ";
    for (int i=0;i<num0.size()-1;i++)
    cout << num0[i] << ", ";
    cout << num0[num0.size()-1];
    cout<<" ].";
    cout << endl;

    for(j=0;j< pow(2,n);j++) {

    vector<int>vnum;
    int fnum=0;

    fnum=num0[j];

    int num=fnum;
    int i=0;

    for(i=0;num>2;i++)//frist push LSB
    {

    vnum.push_back(num%2);
    num=num/2;
    }
    vnum.push_back(num%2);

    int a=1;

    num1.push_back(0);//add 0 in the MSB
    for (i=1;i<=vnum.size();i++)
    num1.push_back(vnum[vnum.size()-i]);

    //generate gray code in binary
    for (int i=0;i<num1.size()-1;i++)
    num2.push_back(num1[i]^num1[i+1] );

    //generate gray code in align
    num4=num2;

    int s=0;
    int k=0;
    s=n-num1.size();

    for(k=0;k<=s;k++){
    num4.push_back(0);
    }

    //grey to normal-binary
    int c=0^num2[0];
    num3.push_back(c);
    for (int i=1;i<num2.size();i++)
    {
    c=c^num2[i];
    num3.push_back(c);

    }

    //display

    for (int i=0;i<num4.size();i++)
    cout << num4[i] << " ";
    cout <<" - "<<fnum<< endl;
    num1.clear( );
    num2.clear( );
    num3.clear( );
    num4.clear( );
    }

    return 0;
    }

  • 相关阅读:
    继承映射
    一对多,多对一,自关联的配置
    Spring 配置自动扫描spring bean配置
    Dao 处理
    2019暑假集训 括号匹配
    2019暑假集训 BLO
    2019暑假集训 Intervals
    2019暑假集训 平板涂色
    2019暑假集训 走廊泼水节
    0002-五层小山
  • 原文地址:https://www.cnblogs.com/nyc1893/p/4573540.html
Copyright © 2011-2022 走看看