【Leetcode】之String to Integer (atoi)

来源:互联网 发布:网红用什么软件拍照 编辑:程序博客网 时间:2024/05/16 20:27

问题描述:

Implement atoi to convert a string to an integer.

我的解题思路:

这道题是一个细节设计题,需要考虑多种边界条件和溢出的情况。个人觉得这种类型的题目意义不是很大,程序如下:

class Solution {public:    int myAtoi(string str) {        if(((str[0]-'0'<0)||(str[0]-'9'>0))&&(str[0]!='+')&&(str[0]!='-')&&(str[0]!=' '))    {        return 0;    }    int flag=1,index=0;    double answer=0;    while(str[index]==' ')    {        index++;    }    if(str[index]=='+')    {        flag=1;        index++;    }    else if(str[index]=='-')    {        flag=-1;        index++;    }    for(int i=index,s=str.length();i<s;i++)    {        if((str[i]>='0')&&(str[i]<='9'))        {            answer=(str[i]-'0')+answer*10;        }        else        {            break;        }    }    answer=answer*flag;    if(answer>2147483647)    {        return 2147483647;    }    else if(answer<-2147483648)    {        return -2147483648;    }    else    {        return answer;    }    }};
0 0
原创粉丝点击