第三章:数据决定数据结构

习题

2

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;
int main()
{
	int k, m;
	k = 1;
	cout << "input the base number up limited number m";
	cin >> m;
	ifstream in;
	in.open("k.txt");
	vector<int> v(m + 1, 0);
	while (in >> v[k]) k++;
	for (int t = k; t <= m; t++)
		for (int j = t-k + 1; j <= t-1; j++)
			v[t] += v[j];
		
	for (int c = 1; c <= m; c++)
		cout << v[c] << endl;
	
}
当k = 2时,可以轻松实现数组记录的fibinacci数列


5.注意无论是否使用二分查找,都是从右向左进行的

7.使用3个位来表示7段显示器上的7段,因此我们其实仅仅需要3*5个位就可以用7段显示器来表示5位数,利用位图

#include <stdio.h>
#define SHIFT 3 // we need to move to another char by 8 bits
#define MASK 0x0F//one byte is 8 bits so we need 8 bits all the time

//we at most need 16 bits so we just need a two char array
char a[2];
void set(int i) {a[i >> SHIFT] |= (1 << (i & MASK)); }//we will only set the last 8 bits
void clc(int i) {a[i >> SHIFT] &= ~(1 << (i & MASK)); }
int test(int i) {return a[i >> SHIFT] & (1 << (i & MASK)); }

int main()
{
	int j = 0;
	for (j; j < 16; j++)
		clc(j);
	set(1);
	set(3);
	set(7);
	int i = 0;
	for (i; i < 16; i++)
	{
		if (test(i)) printf("%d\n", i);
	}
}


Guess you like

Origin blog.csdn.net/juttajry/article/details/51224226