注:代码运行环境为:Ubuntu Linux12.04,gcc 4.6.3
昨天面试了赶集网,感觉很不爽。详细记录如下。
赶集网宣讲去听了宣讲,宣讲完就笔试。笔试题目分两部分,第一部分是基础题,第二部分是编码题。笔试没有通过,强面的,结果失败。
第一部分只做了一个题,其他三个都是选做题。题目是这样的:
int **p; int *p1; int *p2; int i = 1; int j = 2; int k = 3; p1 = &i; p2 = &j; p = &p1; *p = p2; *p = &k;
#include <stdio.h> int main() { int **pp; int *p1; int *p2; int i = 1; int j = 2; int k = 3; p1 = &i; p2 = &j; pp = &p1; *pp = p2; printf("**pp = %d, *p1 = %d\n", **pp, *p1); *pp = &k; printf("**pp = %d, *p1 = %d\n", **pp, *p1); return 0; }
程序运行结果如下:
解释:
p1指向i,p2指向j。pp指向p1,一旦改变pp所指向的内容(即给*pp赋值),则p1的内容会跟着改变。如:*pp = p2,则p1指向p2所指向的内存。也许这个用图更直观些,但是现在能力有限。。。
第二部分:
1.整数的反转,不可将数字转换成数组或者字符串。如12345,返回结果54321。
#include <stdio.h> int main() { int n = 0; scanf("%d", &n); int res = 0; while(n) { res = res * 10 + n %10; n = n / 10; } printf("%d\n", res); return 0; }
运行结果如下:
在考场上,我还将n分成正数和负数,真是“想少了”。因为 负数%10依然的负数, 负数/10依然的负数,so。。。。
2.填补字符串
函数原型如下:
char * strAdd(char *str, int len, char *addstr, int type)
str:源字符串,即往此字符串添加addstr
len:添加后字符串的长度,如果该长度小于源字符串长度则返回源字符串
addstr:要添加的字符串
type:添加方式如下
2:在源字符串的两端添加。比如str = "hello", len = 10, addstr = "*#", type = 2,则结果为:"*#hello*#*"
1:在源字符串的左端添加。比如str = "hello", len = 10, addstr = "*#", type = 2,则结果为:"*#*#*hello"
0:在源字符串的右端添加(默认操作)。比如str = "hello", len = 10, addstr = "*#", type = 2,则结果为:"hello*#*#*"
#include <stdio.h> #include <string.h> #include <stdlib.h> void strAddCore(char *newStr, char *str, char *addStr, int left, int right) { int i = 0; int j = 0; int pos = left; int strLen = strlen(str); int addStrLen = strlen(addStr); //先填写中间的 for(i = 0; i < strLen; i++) newStr[pos + i] = str[i]; //填写左边的 i = 0; while(i < left) { for(j = 0; j < addStrLen && i < left; j++) newStr[i++] = addStr[j]; } //填写右边的 i = 0; j = 0; pos = left + strLen; while(i < right) { for(j = 0; j < addStrLen && i < right; j++) { newStr[pos + i] = addStr[j]; i++; } } return; } char * strAdd(char *str, int len, char *addStr, int type) { if(str == NULL) return NULL; int strLen = strlen(str); if(addStr == NULL || len <= strLen) return str; char *newStr = (char *)malloc((len+1)*sizeof(char)); if(newStr == NULL) { printf("malloc error\n"); return NULL; } newStr[len] = '\0'; int diff = len - strLen; int left = 0; //表示左边要添加的长度 int right = 0; //表示右边要添加的长度 switch(type) { case 2: left = diff >> 1; right = diff - left; //如果diff是奇数,则right会比left多1 break; case 1: left = diff; right = 0; break; case 0: left = 0; right = diff; break; default: break; } strAddCore(newStr, str, addStr, left, right); return newStr; } int main() { char *newStr1 = strAdd("hello", 10, "*#", 2); printf("%s\n", newStr1); char *newStr2 = strAdd("hello", 10, "*#", 1); printf("%s\n", newStr2); char *newStr3 = strAdd("hello", 10, "*#", 0); printf("%s\n", newStr3); free(newStr1); free(newStr2); free(newStr3); return 0; }运行结果如下: