Visual Studio开始一个工程(包含头文件.h 源文件.cpp .cpp)


以leetcode第89题格雷编码作为项目

格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。
给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。即使有多个不同答案,你也只需要返回其中一种。
格雷编码序列必须以 0 开头。

1.新建一个工程

在这里插入图片描述在这里插入图片描述

2.工程结构

头文件 Gray.h
头文件声明方法的实现代码 Gray.cpp
main函数 main.cpp
在这里插入图片描述

3.头文件 .h

声明类(包括成员和方法)

#ifndef — #define — #endif:用来避免同一个文件被include多次,宏名可自取
与 #program once 作用相同

#ifndef GRAY_H
#define GRAY_H

#include<vector>
using namespace std;
class Gray
{
public:
	vector<int> grayCode(int n);
};

#endif

4.源文件 .cpp

4.1实现头文件中声明的方法

注意 include 头文件

#include "Gray.h"

vector<int> Gray::grayCode(int n)
{
	vector<int> dp = { 0 };
	for (int i = 1; i <= n; ++i) {
		for (int j = pow(2, i - 1); j <= pow(2, i) - 1; ++j) {
			dp.push_back(j ^ (j / 2));
		}
	}
	return dp;
}

4.2主函数

代码 system(“pause”); 暂停窗口确保不会一闪而过

#include "Gray.h"
#include <vector>
#include <iostream>
using namespace std;

int main() {
	Gray a;
	vector<int> res = a.grayCode(3);
	for (int i = 0; i < res.size(); ++i) {
		cout << res[i] << endl;
	}
	system("pause");
	return 0;
}

5.运行

main函数中给出n的大小为3
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章