[筆試]判斷迴文數

今天參加了恆生電子的實習生筆試,雞蛋,數據庫的完全不會,看來要看的東西還有很多啊。

筆試最後一題是寫一個算法來判斷迴文字符串,比如“ABCDCBA”。

後來重新在機子上跑了下,唉。。。果然考試的時候貌似把指針寫錯了,而且還寫的太複雜了,指針這東西真心略煩啊。



C++代碼

/*
 *作者:RogerKing
 *郵箱: [email protected]
 *日期:2014/5/11 星期日
 */

#include <iostream>
#include <string>

using namespace std;

void IsPalindrome(char  *s)
{
	char *beg=s;
	char *end=beg+strlen(s)-1;

	while(beg<end)
	{
		if( *beg++ != *end--)
			cout <<s<<"不是迴文"<<endl;
	}
	cout <<s<<"是迴文"<<endl;

}
int main()
{
	char A[100];
	cout<<"輸入字符串:"<<endl;
	cin>>A;
	IsPalindrome(A);
	return 0;
}

還可以這樣寫

#include <iostream>
#include <string>

using namespace std;

void IsPalindrome(char *str)
{
	int start = 0, end;
	end = strlen(str) - 1;
	while(end - start >= 1)
	{
		if(str[start] != str[end])
			cout <<str<<"不是迴文"<<endl;;
		++start;
		--end;
	}
	cout <<str<<"是迴文"<<endl;
}
int main()
{
	char A[100];
	cout<<"輸入字符串:"<<endl;
	cin>>A;
	IsPalindrome(A);
	return 0;
}


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