String to Integer (atoi)【易】

来源:互联网 发布:云顶娱乐软件下载 编辑:程序博客网 时间:2024/05/18 14:22

String to Integer (atoi)

自己实现atoi函数完成字符串转成整数

难度:易

题目比较容易,但是输入很恶心,各种空格、+-符号。代码写的比较乱==‘

例子:

“+123”   123

“-123”  123

“123”  123

“    +123”  123

“+123   ”   123

“+  123” 0

“   +123 4” 123

class Solution {public:    int myAtoi(string str) {        int iResult = 0;        int iLen = str.length();        int i = 0;        int flag = 0;//表示没有正负号,如果为-1表示为负数,如果为1表示为整数                for(i = 0; i < iLen; i ++)        {            if(str[i] == ' ')                continue;            else                break;        }                if(str[i] == '+')            flag = 1;        if(str[i] == '-')            flag = -1;                if(flag == 1 || flag == -1)            i ++;                if(flag == 0)            flag = 1;                for(; i < iLen; i ++)        {            if(str[i] < '0' || str[i] > '9')            {                break;            }            if(iResult > 214748364)            {                if(flag == 1)                    iResult = 2147483647;                else iResult = 2147483648;                                break;            }            if(iResult == 214748364)            {                if(str[i] >= '8')                {                    if(flag == 1)                        iResult = 2147483647;                    else iResult = 2147483648;                                    break;                }            }              iResult = iResult * 10 + str[i] - '0';            std::cout<<iResult<<std::endl;        }                if(flag == 1 && iResult == -2147483648)            iResult = 2147483647;                return iResult * flag;    }};


0 0
原创粉丝点击