String to Integer (atoi) C++实现

来源:互联网 发布:windows gdi 图形编程 编辑:程序博客网 时间:2024/06/08 04:02

问题详见:String to Integer (atoi)

将函数atoi实现出来。题目描述如下:
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.

解题思路:

      实现atoi函数的算法看似简单,不过是将字符串中的一串数字转为一个整数,但是其苛刻的要求使得实现起来要考虑的东西比较多,也因此WA了很多次。该函数的要求有:
      1.该函数首先丢弃尽可能多的空格字符,直到找到第一个非空格字符。然后,从该字符开始,选择一个可选的初始正号或负号,后跟尽可能多的数字,并将其解释为数值。
      2.该字符串可以包含形成整数之后的其他字符,这些字符将被忽略,并且不影响此函数的行为。也就是说一旦在选定了正负号以后如果在向后查找过程中遇到非数字字符即为判定的数字串的结束条件。
      3.如果str中的第一个非空白字符序列不是有效的整数,或者由于str为空或仅包含空格字符,否则不存在此类序列,则不进行转换。
      4.如果不能执行有效的转换,则返回零值。如果正确的值超出可表示值的范围,则返回INT_MAX(2147483647)或INT_MIN(-2147483648)。
      具体的C++实现算法如下:

class Solution {public:    int myAtoi(string str) {        long ans=0;        bool tag=true;        for(int i=0;i<str.length();){            while(str[i]==' ') ++i;            if(str[i]=='-'||str[i]=='+'){                tag=(str[i]=='-')?false:true;                ++i;            }            while(str[i]>='0'&&str[i]<='9'){                ans=ans*10+(str[i]-'0');                if(tag&&ans>=INT_MAX)    return INT_MAX;                if(!tag&&-ans<=INT_MIN)    return INT_MIN;                ++i;            }            return (tag?ans:-ans);        }        return (tag?ans:-ans);    }};

上述算法提交运行结果如下:
atoi

0 0
原创粉丝点击