【leetcode】8. String to Integer (atoi)

来源:互联网 发布:笑傲江湖知乎 编辑:程序博客网 时间:2024/05/29 02:27
/** * Implement atoi to convert a string to an integer. * * Hint: Carefully consider all possible input cases. If you want a challenge,  * please do not see below and ask yourself what are the possible input cases. * * Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). * You are responsible to gather all the input requirements up front. * */#include <iostream>#include <string>#include <vector>#include <stdio.h>#include <limits.h>using namespace std;//最大:2147483647//最小:-2147483648int myAtoi(string str) {    long ret = 0;    int tmp = 0;    int i = 0;    int flag = 1; //默认正整数    if (str.length() > 0 && (str[0] =='+' || str[0] =='-'))    {        if (str[0] == '-')        {            flag = -1;        }        i = 1;    }    for (; i < str.length(); i++)    {           tmp = str[i] - 48;        if (flag ==1 && (ret > INT_MAX / 10 || ret == INT_MAX / 10 && tmp > INT_MAX % 10))        {            return INT_MAX;        }        else if (flag == -1 && (ret > (unsigned)INT_MIN / 10 || (ret == (unsigned)INT_MIN / 10 && tmp > (unsigned)INT_MIN % 10)))        {            return INT_MIN;        }        if (tmp >= 0 && tmp <= 9)            ret = ret * 10 + tmp;    }    return flag == 1 ? ret : -ret;}int main(){    string s = "-2147483659";    cout << INT_MIN << endl;    cout << myAtoi(s);    system("pause");    return 0;}
0 0