部分IT公司笔试算法题
1、将一整数逆序后放入一数组中(要求递归实现)
void convert(int *result, int n) {
if(n>=10)
convert(result+1, n/10);
*result = n%10;
}
int main(int argc, char* argv[]) {
int n = 123456789, result[20]={};
convert(result, n);
printf("%d:", n);
for(int i=0; i<9; i++)
printf("%d", result);
}
2、求高于平均分的学生学号及成绩(学号和成绩人工输入)
double find(int total, int n) {
int number, score, average;
scanf("%d", number);
if(number != 0) {
scanf("%d", score);
average = find(total+score, n+1);
if(score >= average)
printf("%d:%d\n", number, score);
return average;
} else {
printf("Average=%d\n", total/n);
return total/n;
}
}
int main(int argc, char* argv[]) {
find(0, 0);
}
3、递归实现回文判断(如:abcdedbca就是回文,判断一个面试者对递归理解的简单程序)
int find(char *str, int n) {
if(n<=1) return 1;
else if(str[0]==str[n-1]) return find(str+1, n-2);
else return 0;
}
int main(int argc, char* argv[]) {
char *str = "abcdedcba";
printf("%s: %s\n", str, find(str, strlen(str)) ? "Yes" : "No");
}
4、组合问题(从M个不同字符中任取N个字符的所有组合)
void find(char *source, char *result, int n) {
if(n==1) {
while(*source)
printf("%s%c\n", result, *source++);
} else {
int i, j;
for(i=0; source != 0; i++);
for(j=0; result[j] != 0; j++);
for(; i>=n; i--) {
result[j] = *source++;
result[j+1] = '\0';
find(source, result, n-1);
}
}
}
int main(int argc, char* argv[]) {
int const n = 3;
char *source = "ABCDE", result[n+1] = {0};
if(n>0 & strlen(source)>0 && n<=strlen(source))
find(source, result, 3);
}
5、分解成质因数(如435234=251*17*17*3*2,据说是华为笔试题)
void prim(int m, int n) {
if(m>n) {
while(m%n != 0) n++;
m /= n;
prim(m, n);
printf("%d*", n);
}
}
int main(int argc, char* argv[]) {
int n = 435234;
printf("%d=", n);
prim(n, 2);
}
6、寻找迷宫的一条出路,o:通路; X:障碍。(大家经常谈到的一个小算法题)
#define MAX_SIZE 8
int H[4] = {0, 1, 0, -1};
int V[4] = {-1, 0, 1, 0};
char Maze[MAX_SIZE][MAX_SIZE] = {{'X','X','X','X','X','X','X','X'},
{'o','o','o','o','o','X','X','X'},
{'X','o','X','X','o','o','o','X'},
{'X','o','X','X','o','X','X','o'},
{'X','o','X','X','X','X','X','X'},
{'X','o','X','X','o','o','o','X'},
{'X','o','o','o','o','X','o','o'},
[1] [2] [3] [4] [5] [6] [7] [8] 下一页