笔试题一:
解题思路:
使用一个指针i对输入字符串进行扫描,统计出最深的层次,指针start和end分别指向最深的左括号和右括号,如下图所示
测试效果:
代码:
/*
* 2014 BaoFengYingYin XiaoYuan Recruitment
* to find a deepest expression in a string
* Input: X + ((Y - 6) * 2) + (((2 * 3) / 2Y) + I) / (2 * 6Y)
* Output: 2 * 3
* */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 1024
int DeepestMatch(char *str) {
int i;
int lay, maxlay; // the lay of Kuhao
int start, end;
int check; // whether the Kuhao match
maxlay = 0;
lay = 0;
check = 0;
for(i = 0;str[i];i++) {
if(str[i] == '(') {
lay++;
check++;
}
else if(str[i] == ')') {
check--;
if(lay > maxlay) {
maxlay = lay;
end = i;
lay = 0;
}
}
}
if(check) {
perror("Kuhao Mismatch!\n");
exit(EXIT_FAILURE);
}
if(!maxlay) {
perror("there is no kuhao in the expression!\n");
return 0;
}
start = end;
while(str[start] != '(') start--;
puts("the deepest expression in the string is:");
for(i = start+1;i < end;i++) {
putchar(str[i]);
}
putchar('\n');
return 0;
}
int main() {
char str[SIZE];
memset(str, 0, sizeof(str));
printf("Input a expression:");
gets(str);
DeepestMatch(str);
return 0;
}
编程体会:本来想用到堆栈,其实也不需要,最主要的扫描真个字符串,找到最深的左括号,即找到了目标。
试题二:
解题思路:对比两个IP地址,找到不同的数字,比如上述的两个IP地址:172.16.2.64到172.16.2.127,他们只有64和127不同,将64和127转为二进制是
01 0000001, 01 111111,那么低6位不同,这就是子网内主机的范围,而子网掩码共育3 × 8 + 2 = 26个1
测试:
代码:
/*
* to convert two IP address into a mask IP address
* 2014 Baofengyingyin xiaoyuan recruitment
*/
#include <stdio.h>
#include <stdlib.h>
#define LEN 4
#define MAX 256
/*
* to define a two 32 bits IP address
*/
int IP1[LEN];
int IP2[LEN];
/*
* to input a IP address
*/
void InputIPAddr(int *arr) {
int i;
int e;
for(i = 0;i < LEN;i++) {
if(scanf("%d", &e) != 1) {
perror("Input error!\n");
exit(EXIT_FAILURE);
}
else if(e < 0 || e > MAX) {
perror("Input error!\n");
exit(EXIT_FAILURE);
}
*arr++ = e;
}
}
/*
* for example 172.16.2.64 and 172.16.2.127
* 64 and 127 is a and b
*/
int Mask(int a, int b) {
int tmp1[8];
int tmp2[8];
memset(tmp1, 0, sizeof(tmp1));
memset(tmp2, 0, sizeof(tmp2));
int i;
int k;
for(i = 7; i >= 0 && a;i--) {
tmp1[i] = a%2;
a /= 2;
}
for(i = 7;i >=0 && b;i--) {
tmp2[i] = b%2;
b /= 2;
}
k = 0;
i = 0;
while(tmp1[i] == tmp2[i]) {
k++;
i++;
}
return k;
}
/*
* to find different mask
*/
int FindMask() {
int i;
int k = 0;
for(i = 0;i < LEN;i++) {
if(IP1[i] == IP2[i]) k += 8;
else break;
}
if(i < LEN) k += Mask(IP1[i], IP2[i]);
return k;
}
int main() {
printf("please input the first IP Address:\n");
InputIPAddr(IP1);
printf("please input the second IP Address:\n");
InputIPAddr(IP2);
printf("the mask IP Address is:");
int i;
for(i = 0;i < LEN;i++) {
printf("%d", IP1[i]);
if(i < LEN - 1) putchar('.');
}
putchar('/');
int k = FindMask();
printf("%d\n", k);
return 0;
}
编程体会:最重要的搞清题目中子网掩码到底由多少个1构成。