8、String to Integer (atoi)

来源:互联网 发布:java unicode码转中文 编辑:程序博客网 时间:2024/05/29 15:39

题目:

mplement 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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

spoilers alert... click to show requirements for atoi.

解题思路:

1. 字串为空,返回0; 

2. 字串的前缀空格需要忽略掉;

3. 遇到的第一个字符,如果是‘+’或‘-’号,将符号标识为相应值;

4. 处理数字;

5. 在上述处理过程中,如果转换出的值超出了int型的范围,就返回int的最大值或最小值。


C++版本:

class Solution {public:    int myAtoi(string str) {        long long res = 0;        int minus = 1;                if(str!="")        {            while(str.size()>0 and str[0]==' ')    //正负号前面有空格  如"     -123"                str.erase(str.begin());                        if(str[0]=='-')       //正负号处理            {                minus=-1;                str.erase(str.begin());            }            else if(str[0]=='+')            {                minus=1;                str.erase(str.begin());            }        }                for(char c : str)        {            if(res>INT_MAX)                    //超出int 范围                break;            else if(isdigit(c))                   //如果是数字                res = 10*res + c-'0';            else                               //特殊符号处理 如"-+123" -> 0                return minus*res;        }                if(minus*res>INT_MAX)            return minus*INT_MAX;        if(minus*res<INT_MIN)            return minus*INT_MIN;                return minus*res;    }};


python版本:

class Solution(object):    def myAtoi(self, str):        """        :type str: str        :rtype: int        """        INT_MAX = 2147483647; INT_MIN = -2147483648        index,res = 0,0        sign = True        if(str==""):return 0;        while(index<len(str) and str[index]==" "):            index += 1        if(index<len(str) and (str[index]=="+" or str[index]=="-")):            if(str[index]=="-"):                sign = False            index += 1        while(index<len(str) and str[index]>='0' and str[index]<='9'):            res = 10*res+int(str[index])            if(res>INT_MAX):                if(sign):return INT_MAX                else:return INT_MIN            index += 1        if(sign==False):return -res        return res



0 0