格雷码的递归输出

来源:互联网 发布:时间管理软件 知乎 编辑:程序博客网 时间:2024/06/08 20:02

//第一种

#include <math.h>

#include "stdlib.h"
#include "stdio.h"
void CreateGrayCode(int n,int x) //x初始值为0
{
    if(x<pow(2,n))
    {
        int graycode=(x^(x>>1));
        char buf[32];
        printf("%032s\n",itoa(graycode,buf,2));
         CreateGrayCode(n,x+1);
    }
}
int main()
{
  CreateGrayCode(10,0);
  return 0;

}

//第二种

#include <iostream>
#include <math.h>
#include <vector>
#include <string>
using namespace std;
vector<string> getGray(int n) {
        // write code here
        int N=pow(2,n);
        static int i=0;
        static vector<string> vc;
        if(i<N)
        {
            char temp[256];
            sprintf(temp,"%d",i^(i>>1));
            vc.push_back(temp);
            ++i;
            getGray(n);
            
        }
       return vc;
    }



0 0
原创粉丝点击