百度开发工程师的面试题(导航部门)

1. 程序改错题:

#include "string.h"
#define TONUM(x) x - '0'

int matoi(char* p) 
{
    int i ;
    int res; 
    for (i = 0; i < strlen(p);i++)
    {
        res = res * 10 + TONUM(p[i]); 
    }
    return res;        //容易溢出
}

//首先理解本题目的愿意,即本题目是将用字符串表示的整数转换成真正的字符串

总共错误有3处

错误1:字符串没有做合法性检验,非空,只有数字等;

错误2:res局部变量没有初始化,导致计算溢出;

错误3:没有考虑大数超过INT数值的范围

错误4:没有考虑负数的可能性---面试时没有考虑到

修改结果如下(不考虑负数):

#include "string.h"
#define TONUM(x) x - '0'

int matoi(char* p) //未检查p的合法性
{

    int i ;
    int res = 0; //错误1没有初始化
    if (NULL == p)return -1;
    if (p[0] == '0')return -1;
    for (i = 0; i < strlen(p);i++)
    {
        if (p[i] < '0' || p[i] > '9')return -1;
        res = res * 10 + TONUM(p[i]);
        if(IsOverFlow(res))return res;
    }
    return res;        //容易溢出
}

2.//删除链表指定value的节点,其中不考虑根节点

Node* DeleteList(int iValue)
{
    if (NULL == head)return NULL;
    Node* cur = head;
    Node* temp = head->next;
    while (temp)
    {
        if (temp->data == iValue){
            cur->next = temp->next;
            free(temp);
            temp = cur->next;
        }
        else{
            cur  = temp;
            temp = temp->next;
        }
    }
    if (head->data == iValue){//如果考虑根节点的话,增加这样一段。
        temp = head;
        head = head->next;
        free(temp);
        temp = NULL;
    }
    return head;

}

Node* DeleteListNormal(int iValue)
{
    if (NULL == head)return NULL;

    Node* cur  = head;
    Node* next = head->next;

    while (cur)
    {
        if (iValue == cur->data)
        {
            if (cur == head)head = cur->next;
            next = cur;
            cur = cur->next;
            free(next);
            next = cur->next;
        }
        else
        {
            cur = next;
            next = next->next;
        }
    }
    return head;
}

3. 排序几百亿的数据,参考如下:

http://www.epubit.com.cn/article/301

猜你喜欢

转载自blog.csdn.net/w1012747007/article/details/77415923