String to Integer (atoi)

来源:互联网 发布:2018优化方案丛书官网 编辑:程序博客网 时间:2024/04/28 08:56

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.

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.

Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

第一次提交代码:

class Solution {public:    int myAtoi(string str) {        int resultToResult = 0;        int flag = 1;        bool have_character = false;        if(str.size() == 0)            return 0;        for(size_t index = 0; index < str.size(); index++)        {            if(str[index] == '+' && !have_character)            {                have_character = true;                continue;            }            else if(str[index] == '-' && !have_character)            {                have_character = true;                flag = -1;                continue;            }            else if((str[index] == '+' || str[index] == '-') && have_character)            {                resultToResult = 0;                break;            }            else if((str[index] == ' ' || str[index] == '0') && resultToResult == 0)            {                continue;            }            else if(!isdigit(str[index]))                break;            resultToResult = resultToResult * 10 + str[index] - '0';        }        return flag * resultToResult;    }};

但是代码中添加了太多的条件判断语句,并且第一次提交代码没有通过,结果如下:

这里写图片描述

后来看了给出的提示,并查找了一些资料,重新提交代码:

class Solution {public:    int myAtoi(string str) {    long long cur=0;    int num=0,i=0;    int flag1=0,flag2=0;    while(str[i]!='\0' && str[i]==' ') i++;//开头空格舍弃    if(str[i]=='-') flag1++,i++;    else if(str[i]=='+') flag2++,i++;    for(; str[i]!='\0'; i++)    {        if(str[i]>='0' && str[i]<='9')        {            if(flag1==2)            {                cur=cur*10-(str[i]-'0');//这里是减法,因为cur符号是负号了                if(cur<INT_MIN) return INT_MIN;            }            else if(flag1==1) cur=-str[i]+'0',flag1++;//将负数的符号记录到cur里            else            {                cur=cur*10+(str[i]-'0');                if(cur>INT_MAX) return INT_MAX;            }        }        else break;    }    num=(int)cur;    return num;    }};

总结

  1. 处理数字时一定要先判断是否在0~9之内
  2. 注意数字的符号,0以及是否溢出
0 0
原创粉丝点击