求N位格雷码(递归版and循环版and位运算版)

#include <iostream>
#include <vector>
using namespace std;

vector<string> func(size_t n){
	vector<string> res{};
	if(n == 0) return res;
 	if(n == 1){
	 	res = {"0","1"};
	 	return res;
	 }
	 res = func(n - 1);
	 vector<string> vStr;
	 for(auto s : res) vStr.push_back("0" + s);//纸上写的时候漏写了auto。。。
	 for(auto ps = res.end() - 1;ps >= res.begin();--ps){ //纸上写代码的时候居然写成 for(auto ps = res.end() - 1;i != res.begin();--i),真是太粗心了!!
	 	string tem = *ps;
	 	vStr.push_back("1" + tem);
	 } 
	 
	 return vStr;
}

int main(int argc, char *argv[])
{
	for(auto s : func(5))
		cout << s << endl;
	return 0;
}
#include <iostream>
#include <vector>
using namespace std;

vector<string> func(size_t n){
    vector<string> res{};
    if(n == 0) return res;
	size_t time = 1;
	res.push_back("0");
	res.push_back("1");
	while(time++ < n){
		size_t oldLen = res.size();
		for(size_t t = oldLen - 1;t != -1;--t){
			string tem = res[t];
			tem = "1" + tem;
			res.push_back(tem);
		}
		
		size_t newLen = res.size();
		for(size_t i = 0;i != newLen / 2;++i)
			res[i] = "0" + res[i];
	}
	
	return res;
}

int main(int argc, char *argv[])
{
	for(auto s : func(3))
		cout << s << endl;
	return 0;
}

补充:

#include <iostream>
#include <vector> 
using namespace std;

vector<int> getGrayCode(int n){
	int num = 1 << n;
	vector<int> res;
	for(int i = 0; i != num;++i){
		int tem = (i >> 1) ^ i;
		res.push_back(tem);
	}
	return res;
}
int main(int argc, char *argv[])
{
	for(auto i : getGrayCode(5))
		printf("%x\n",i);	//这种风格真丑,奈何C++输出16进制不方便,偷下懒~
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值