DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Test

09.01.2006
| 999 views |
  • submit to reddit
        // description of your code here

//1:递归的就3行解决问题,�过呢比较挫的机�上溢出,整个�递归的
unsigned int Fibonacci(unsigned int a)
{
	unsigned int tmp[2]={0,1};
	bool flag = true;
	if(a == 0) return 0;
	if(a == 1) return 1;
	for(int i = 0; i < a-1; i++)
	{
		tmp[!flag] += tmp[flag];
		flag = !flag;
	}
	return tmp[flag];

}
void problem1(char* filename)
{
	ifstream infile(filename);
	assert(filename);
	int val;
	while(infile>>val)
         {cout<<Fibonacci(val)<<endl;}
	infile.close();
}

//2:就一体力活。。。
const static char keys[][13]=
{
	{'`', '1', '2', '3', '4', '5' ,'6', '7' ,'8' ,'9', '0', '-' ,'='},
	{'Q', 'W', 'E', 'R', 'T' ,'Y', 'U', 'I', 'O', 'P' ,'[', ']', '\\'},
	{'A' ,'S' ,'D' ,'F' ,'G' ,'H' ,'J', 'K' ,'L' ,';', '\''},
	{'Z',  'X' , 'C',  'V' , 'B' , 'N',  'M',  ',' , '.',  '/'}
};
static unsigned char charmap[256];
void buildmap()
{
	int i, j;
	for(i = 0; i < 256; i++)charmap[i] = i;
	for(j =0; j < 4; j++)
	for(i = 1; i < 13; i++)
	{
		if(keys[j][i])
		{
			charmap[keys[j][i]] = keys[j][i-1];
			if(keys[j][i] >= 'A' && keys[j][i] <= 'Z')
				charmap[keys[j][i]+32] = keys[j][i]+32;
		}
	}
	
}

void problem2(const char* filename)
{
	static bool isinitmap = false;
	int chr;
	FILE *fp = fopen(filename, "r");
	assert(filename);
	if(!isinitmap){ buildmap(); isinitmap = true;}
	while((chr = fgetc(fp)) != EOF)
	{
		printf("%c", (char)charmap[chr]);
		
		
	}
	fclose(fp);
	
}
#if 0
3:如果对STL的string有那么一点点了解的�会比较简�,如果想裸写KMP,
还是比较困难,�过暴力的O(m*n)的倒是简�,估计也能accept :-)
#endif 
typedef basic_string<char>::size_type str_pos;
int string_shift(string& T, string P)
{
	str_pos start = -1;
	int shift_cnt = 0;
	while((start = T.find(P, start+1)) != -1)shift_cnt++;
	return shift_cnt;
}
void strshift(char* filename)
{
	ifstream infile(filename);
	assert(infile);
	string T, P;
	while(infile>>T>>P)cout << string_shift(T, P)<<endl;
	infile.close();
}

//4:一个简�的办法就是递归啦,�过注�2的表示是2 �是2(2(0))就好了。
#define BITMASK (0x1<<31)
void exponentform(unsigned int a)
{
	if(a == 0 || a == 2)
	{
		cout << a;
		return;
	}
	for(int i = 31; i > -1; i--)
	{
		if(a & BITMASK)
		{
			if(i == 1)
			{
				cout << "2";
			}
			else 
			{
				cout<<"2(";
				exponentform(i);
				cout << ")";
			}
			if(a<<1)cout << "+";
			//
		}
		a <<= 1;
	}
}

void problem4(char* filename)
{
	ifstream infile(filename);
	int val;
	while(infile>>val)
	{
		exponentform(val);
		puts("");
	}
	infile.close();
}