面试题1----把字符串转换成整数

来源:互联网 发布:古罗马怎么灭亡的 知乎 编辑:程序博客网 时间:2024/04/28 20:50

题目要求:

写一个函数StrToInt实现将字符串转换为整数的功能。 

需要考虑的点

  • 字符串为空串或空指针.
  • 字符串含有非0到9的字符.
  • 特别注意字符串转换到int值,要考虑溢出的问题,正整数的最大值是0x7FFFFFFF,负数的最小值是0x80000000.

代码如下:

#include<iostream>#include<string.h>#include<limits>bool strToInt(const char *str,int &nInt){    if(str == NULL){        std::cout <<"空指针"<<std::endl;        return  false;    }else if(str == ""){        std::cout << "空串"<<std::endl;        return false;    }else if((strcmp(str,"+") == 0) || (strcmp(str,"-") == 0)){        std::cout << "字符串输入无效"<<std::endl;        return false;    }else{        const char *p = str;        bool isFirst = true; //标记是否为字符串的第一个字符        bool hasMinus = false; //标记字符串的第一个字符是否是负号.        nInt = 0;        while(*p != '\0'){            if(isFirst && (*p) == '-' ){                hasMinus = true;                p++;                continue;            }else if(isFirst && (*p) == '+'){                p++;                continue;            }            if((*p) >= '0' && (*p) <= '9'){                nInt = nInt*10+*p-'0';                if((!hasMinus && nInt > std::numeric_limits<int>::max()) || (hasMinus && nInt < std::numeric_limits<int>::min())){                    std::cout << "字符串数值溢出,输入无效!"<<std::endl;                    return false;                }                    p++;                }else{                    std::cout << "字符串中包含有非数字的字符,不能转换为数字"<<std::endl;                    return false;                }        }                    if(hasMinus){                        nInt = (-1) * nInt;                    }                    return true;    }}int main(int argc,char *argv[]){    int nInt = 0;    char *str = NULL;    if(strToInt("123",nInt)){        std::cout << nInt<<std::endl;    }    if(strToInt("",nInt)){        std::cout <<nInt<<std::endl;    }    if(strToInt(str,nInt)){        std::cout <<nInt<<std::endl;    }    if(strToInt("-123",nInt)){        std::cout <<nInt<<std::endl;    }    if(strToInt("+123",nInt)){        std::cout <<nInt<<std::endl;    }    if(strToInt("-#45466@",nInt)){        std::cout <<nInt<<std::endl;    }    if(strToInt("10000000000000000000000000",nInt)){        std::cout <<nInt<<std::endl;    }    if(strToInt("-10000000000000000000000000",nInt)){        std::cout <<nInt<<std::endl;    }   return 0;}
0 0