您的位置:首页 > 其它

华为的最新的两道算法设计题

2013-12-17 00:57 141 查看

要求均用C语言实现

1.找出最大长度子字符串(只包含字母),打印并且返回长度。 例如 str = "abc123abcd234abcdefgha324adsdawqdasdaseqqwe345abchded",最大子字符串是

“adsdawqdasdaseqqwe”

int findMaxSubstring(char* str)
{
int maxLength = 0;
int maxStartIndex = 0;
int curLength = 0;
int curStartIndex = 0;
bool isFind = 0;
for(unsigned int i = 0;i<strlen(str);i++)
{
if(str[i] >= 'a' && str[i] <= 'z')
{
if(isFind == 0)
{
isFind = 1;
curLength = 1;
curStartIndex = i;
}
else
{
curLength++;
}
}
else if (str[i] < 'a' || str[i] > 'z')
{
isFind = 0;
if(curLength > maxLength)
{
maxLength = curLength;
maxStartIndex = curStartIndex;
curLength = 0;
}
}
}
char *p = NULL;
p = &str[maxStartIndex];
while(*p >= 'a' && *p <= 'z')
{
putchar(*p);
p++;
}
return maxLength;
}


2. 一个四位数,如1024,1004,打印出他们的中文形式,如果一千零二十四,一千零四

这题因为限定了4位数,所以只考虑了4位数的情况,吃点分享一个大小写转换的源码,里面有不限位数的情况,当时调试的很痛苦,思想差不多。

void iConvert(int digit)
{
char a[5][10] = {"千","百","十","","零"};
char b[11][10] = {"零","一","二","三","四","五","六","七","八","九","十"};
char result[50] = {'\0'};
int A[4] = {};
for(int i=3;i>=0;i--)
{
A[i] = digit % 10;
digit = int(digit/10);
}
printf("%d,%d,%d,%d\n",A[0],A[1],A[2],A[3]);
int foundZero = 0;
for(int i = 0 ;i<4;i++)
{
if(A[i]>0)
{
strcat(result,b[A[i]]);
strcat(result,a[i]);
}
if(A[i]==0 && foundZero == 0)
{
if(i!=3)//如果不是最后一位,则不追加零
{
strcat(result,a[4]);
foundZero = 1;
}
}
}
puts(result);
}

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: