String to Integer (atoi)-LeetCode

来源:互联网 发布:淘宝王者荣耀点券 编辑:程序博客网 时间:2024/05/08 07:38

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.

class Solution {public:    int atoi(const char *str) {       long long num = 0;    int sign = 1;    const char *stemp = str;    if (stemp == NULL)    {    return 0;    }    while(*stemp == ' ')    {    stemp++;    }    if (*stemp == '+')    {    stemp++;    }    else if (*stemp == '-')    {    sign = -1;    stemp++;    }     while(*stemp == '0')    {    stemp++;    }        while (*stemp >= '0' && *stemp <= '9')    {    num = num * 10 + *stemp - '0';    if (num * sign > INT_MAX)    return INT_MAX;    if (num * sign < INT_MIN)    return INT_MIN;    stemp++;    }    return num * sign;     }};


 

0 0