面试编程题笔记

来源:互联网 发布:ps cs3 mac版 编辑:程序博客网 时间:2024/06/05 14:54

微软:将一个字符串转为整数

初版:

int StringToInt(char*str)

{

    int nInt = 0;

    while (*str != 0)

    {

         nInt = (nInt * 10) + (*str -'0');

         ++str;

    }

 

    return nInt;

}

 

int _tmain(int argc,_TCHAR* argv[])

{

    char* strTestNum = "123456";

    char* strNull = NULL;

 

    cout << "测试转化1:" << StringToInt(strTestNum) << endl;

 

    cout << "测试转化2:" << StringToInt(strNull) << endl;

    return 0;

}

传入空指针则程序崩溃。

注意点:对于函数传入参数,需要考虑其特殊的输入,然后进行相应的处理。

最终版:

#include <iostream>

using namespace std;

 

int StringToInt(char*str)

{

    // 空指针

    if (NULL ==str)

    {

         return -1;

    }

 

    // 负数

    bool bNegative = false;

    if (*str =='-')

    {

         bNegative = true;

         ++str;

    }

 

    int nInt = 0;

    while (*str != 0)

    {

         // 含有特殊字符

         if ((*str <'0') || (*str >'9'))

         {

             return -1;

         }

 

         nInt = (nInt * 10) + (*str -'0');

         ++str;

    }

 

    if (bNegative)

    {

         return -nInt;

    }

 

    return nInt;

}

 

int _tmain(int argc,_TCHAR* argv[])

{

    char* strTestNum1 = "123456";

    char* strTestNum2 = "-123456";

    char* strTestNum3 = "12c456";

    char* strNull = NULL;

 

    cout << "测试转化(正常):" << StringToInt(strTestNum1) << endl;

    cout << "测试转化(负数):" << StringToInt(strTestNum2) << endl;

    cout << "测试转化(特殊字符):" << StringToInt(strTestNum3) << endl;

    cout << "测试转化(空指针):" << StringToInt(strNull) << endl;

    return 0;

}

0 0
原创粉丝点击