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
在這裏插入圖片描述

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