读书人

恒生电子的两道笔试题.该怎么解决

发布时间: 2012-05-04 12:36:09 作者: rapoo

恒生电子的两道笔试题...
1.不用任何库函数,也不能用除s1,s2其他变量,实现对字符串s1的反转。
函数原型为void reverse(const char *s1,char *s2).
2.(题目本来是要求用Java写)函数原型为public int intvert(int x,int p,int n)实现对整数x的二进制形式的部分替换。
是从右端向左数起,在第p位用n替换(也是从右向左的)。例如当p=4,n=3,x=00010001时,替换后的结果为01100001。

题目意思大致是那样的,看看大家都怎么写的。

[解决办法]

C/C++ code
void reverse(const char *s1,char *s2){for( int i = 0; i < strlen(s1); i++)    {        *(s2+strlen(s1)-i-1) = *(s1+i);    }}
[解决办法]
2.
C/C++ code
int intvert(int x,int p,int n){     int m = p;     p = n;     p << m;     return x^p;}
[解决办法]
void reverse(const char *s1,char *s2)
{
*s2='\0';
while(*s1!='\0')
{
++s1;
++s2;
}
*s2='\0';
while (*(--s2)!='\0')
--s1;
--s1;
while(*(++s2)!='\0');
--s2;
while(*s1!='\0')
{
*(s2--)=*(s1++);
}
}
[解决办法]
void reverse(const char *s1,char *s2)
{


while(*s2)
{
s2++;
}
s2--;
while(*s1)
{
*s2 = *s1;
s2--;
s1++;
//*s2
//*s2
}


}

调用前s2要初始化
[解决办法]
C/C++ code
void reverse(const char *s1, char *s2){    if(*s1 != '\0')        f(++s1, s2);     if(*s1 == '\0')    {        *s2++ = *--s1;        *s2 = '\0';        return;    }    else    {   while(*s2 != '\0') ++s2;        *s2++ = *--s1, *s2 = '\0';    }}int main(){    char s1[] = "heat";    char s2[10];    reverse(s1, s2);    cout << s2 << endl;}
[解决办法]
void reverse(const char *s1, char *s2)
{
if(*s1 != '\0')
f(++s1, s2);

if(*s1 == '\0')
{
*s2++ = *--s1;
*s2 = '\0';
return;
}
else
{ while(*s2 != '\0') ++s2;
*s2++ = *--s1, *s2 = '\0';
}

哈哈,递归了
[解决办法]
#include <iostream>

void reverse(const char *s1,char *s2)
{


while(*s2)
{
s2++;
}
s2--;
while(*s1)
{
*s2 = *s1;
s2--;
s1++;
}
}

int main()
{
char s1[] = "123456";
char s2[] = "123456";
reverse("123456",s2);
}
[解决办法]
C/C++ code
10L代码可行:void reverse(const char *s1,char *s2) {   *s2='\0';    //首做个标记  while(*s1!='\0')    {               ++s1;   ++s2;   }   *s2='\0'; //尾做个标记  while (*(--s2)!='\0')     --s1; //将s1移回行首          --s1;   while(*(++s2)!='\0');   --s2; //将s2移到行尾  while(*s1!='\0')   {   *(s2--)=*(s1++); //复制  } }
[解决办法]
void reverse(const char *s1,char *s2)
{
if (s2 == s1)
{
return;
}

if (s2 - s1 > 1)
{
// 改变布局
*(s2 + 1) = *s2;
*s2 = '\0';

reverse(++s1, --s2);
}
else if (s2 - s1 == 1)
{
*(s2 + 1) = *s2;
*s2 = *(s2 - (s2 - s1));
*(s2 - (s2 - s1)) = *(s2 + 1);


*(s2 + 1) = '\0';

return;
}

// 恢复现场,并完成转换
s1--;
s2++;

*s2 = *(s2 - (s2 - s1));
*(s2 - (s2 - s1)) = *(s2 + 1);
*(s2 + 1) = '\0';
}

参数s2指向s1的最后一个字符
[解决办法]

探讨
C/C++ code
10L代码可行:

void reverse(const char *s1,char *s2)
{
*s2='\0'; //首做个标记
while(*s1!='\0')
{
++s1;
++s2;
}
*s2='\0'; //尾做个标记
while (*(--s2)!='\0')
--s1; //将s1移回行首
--s1;
while(*(++s2)!='\0');
--s2; //将s2移到行尾
while(*s1!='\0')
{
*(s2--)=*(s1++); //复制
}
}

读书人网 >C++

热点推荐