C++面試題

1、給定字元串 a 和 b,輸出 a 和 b 中的最大公共子串。
比如 a="aocdfe" b="pmcdfa" 則輸出"cdf"
*/
//author: azhen
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *commanstring(char shortstring[], char longstring[])
{
int i, j;
char *substring=malloc(256);
if(strstr(longstring, shortstring)!=null) //如果„„,那么返回 shortstring
return shortstring;
for(i=strlen(shortstring)-1;i>0; i--) //否則,開始循環計算
{
for(j=0; j<=strlen(shortstring)-i; j++){
memcpy(substring, &shortstring[j], i);
substring[i]='\0';
if(strstr(longstring, substring)!=null)
return substring;
}
}
return null;
}
main()
{
char *str1=malloc(256);
char *str2=malloc(256);
char *comman=null;
gets(str1);
gets(str2);
if(strlen(str1)>strlen(str2)) //將短的字元串放前面
comman=commanstring(str2, str1);
else
comman=commanstring(str1, str2);
printf("the longest comman string is: %s\n", comman);
}
2、寫一個函式比較兩個字元串 str1 和 str2 的大小,若相等返回 0,若 str1 大於str2 返回 1,若 str1 小於 str2 返回-1
int strcmp ( const char * src,const char * dst)
{
int ret = 0 ;
while( ! (ret = *(unsigned char *)src - *(unsigned char *)dst) && *dst)
{
++src;
++dst;
}
if ( ret < 0 )
ret = -1 ;
else if ( ret > 0 )
ret = 1 ;
return( ret );
}
3、求 1000!的未尾有幾個 0(用素數相乘的方法來做,如 72=2*2*2*3*3);
求出 1->1000 里,能被 5 整除的數的個數 n1,能被 25 整除的數的個數 n2,能被 125 整除的數的個數 n3,
能被 625 整除的數的個數 n4.
1000!末尾的零的個數=n1+n2+n3+n4;
#include<stdio.h>
#define num 1000
int find5(int num){
int ret=0;
while(num%5==0){
num/=5;
ret++;
}
return ret;
}
int main(){
int result=0;
int i;
for(i=5;i<=num;i+=5)
{
result+=find5(i);
}
printf(" the total zero number is %d\n",result);
return 0;
}
4、有雙向循環鍊表結點定義為:
struct node
{ int data;
struct node *front,*next;
};
有兩個雙向循環鍊表 a,b,知道其頭指針為:pheada,pheadb,請寫一函式將兩鍊表中 data值相同的結點刪除
bool detelenode(node *pheader, datatype value)
{
if (pheader == null) return;
bool bret = false;
node *pnode = phead;
while (pnode != null)
{
if (pnode->data == value)
{
if (pnode->front == null)
{
pheader = pnode->next;
pheader->front = null;
}
else
{
if (pnode->next != null)
{
pnode->next->front = pnode->front;
}
pnode->front->next = pnode->next;
}
node *pnextnode = pnode->next;
delete pnode;
pnode = pnextnode;
bret = true;
//不要 break 或 return, 刪除所有
}
else
{
pnode = pnode->next;
}
}
return bret;
}
void de(node *pheada, node *pheadb)
{
if (pheada == null || pheadb == null)
{
return;
}
node *pnode = pheada;
while (pnode != null)
{
if (detelenode(pheadb, pnode->data))
{
if (pnode->front == null)
{
pheada = pnode->next;
pheada->front = null;
}
else
{
pnode->front->next = pnode->next;
if (pnode->next != null)
{
pnode->next->front = pnode->front;
}
}
node *pnextnode = pnode->next;
delete pnode;
pnode = pnextnode;
}
else
{
pnode = pnode->next;
}
}
}