[leetcode] String to Integer (atoi)

来源:互联网 发布:淘宝新店扶持政策 编辑:程序博客网 时间:2024/05/22 09:01

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.

思路:逐个遍历,将字符转换为数字

代码:

class Solution {public:    int atoi(const char *str) {        if(str==NULL) return 0;        if(*str=='\0') return 0;        long long res=0;        int flag=1;        while(*str==' '){            str++;        }        if(*str=='-'){            flag=-1;            str++;        }        else if(*str=='+'){            str++;        }        while(isdigit(*str)){            int temp=*str-'0';            res=res*10+temp;            if(res*flag>INT_MAX){                res=INT_MAX;                break;            }            if(res*flag<INT_MIN){                res=INT_MIN;                break;            }            str++;        }        return flag*res;    }};


 

0 0
原创粉丝点击