嵌入式软件工程师面试题
1、将一个链表逆序
LinkList *reverse(LinkList *head) { LinkList *p1,*p2 = NULL,*p3 = NULL; if(head == NULL || head->next == NULL) return head; p1 = head->next; while(p1!=NULL) { p3 = p1->next; p1->next = p2; p2 = p1; p1 = p3; } head->next = p2; // head = p2; return head; }
2,计算一个字节里(byte)里面有多少bit被置1
#include <stdio.h> int comb(const int c) { int count = 0; int i = 0; int cc = c; while(i++<8) { if((cc&1)==1) { count++; } cc = cc>>1; } return count; } int main() { const int c = 0xcf; printf("%d\n",comb(c)); return 1; }
3、在一个字符串中找到可能的最长的子字符串
#include <stdio.h> #include <stdlib.h> #include <string.h> char *commanstring(char shortstring[],char longstring[]) { int i,j; char *substring = malloc(256); if(strstr(longstring,shortstring)!=NULL) return shortstring; for(i=strlen(shortstring)-1;i>0;i--) { for(j=0;j<=strlen(shortstring)-i;j++) { memcpy(substring,&shortstring[j],i); substring[i]='\0'; if(strstr(longstring,substring)!=NULL) return substring; } } return NULL; } void main(void) { char *str1 = "aocdfe"; char *str2 = "pmcdfa"; char *comman = NULL; if(strlen(str1)>strlen(str2)) comman= commanstring(str2,str1); else comman = commanstring(str1,str2); printf("the longest comman string is:%s\n",comman); }
4、字符串转换为整数
#include <stdio.h> #include <string.h> void reverse(char s[]) { //字符串反转 int c, i=0, j; for(j=strlen(s)-1;i<j;j--) { c=s[i]; s[i]=s[j]; s[j]=c; i++; } } void IntegerToString(char s[],int n) { int i=0,sign; if((sign=n)<0)//如果是负数,先转成正数 n=-n; do //从个位开始变成字符,直到最高位,最后应该反转 { s[i++]=n%10+'0'; }while((n=n/10)>0); //如果是负数,补上负号 if(sign<0) s[i++]='-'; s[i]='\0';//字符串结束 reverse(s); } void main() { int m; char c[100]; m =215; IntegerToString(c,m); printf("integer = %d string = %s\n", m, c); }
5、整数转换为字符串
#include <stdio.h> #include <string.h> int Atoi(char str[]) { int i; int weight = 1; // 权重 int rtn = 0; // 用作返回 for(i = strlen(str) - 1; i >= 0; i--) { rtn += (str[i] - '0')* weight; // weight *= 10; // 增重 } return rtn; } void main() { char str[32]; printf("Input a string :"); gets(str); printf("%d\n", Atoi(str)); }
6、将一个字符串逆序
#include <stdio.h> #include <string.h> char *strconv(char *p) { int length = strlen(p); char *ptr = p; char *ptr_1 = p + length -1; while(ptr < ptr_1) { char c = *ptr; *ptr = *ptr_1; *ptr_1 = c; ++ptr; --ptr_1; } return p; } int main() { char str[]="abcdef1234"; char *p; p = strconv(str); printf("%s",p); return 1; }