[LeetCode] String to Integer (atoi) 解题报告

来源:互联网 发布:java 双向链表 编辑:程序博客网 时间:2024/06/09 21:35

—— write for my baby, mua


[题目]

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.


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将字符串转换为数字。

提示:考虑所有可能的输入情况。如果你想有点挑战,请不要看下面的提示,自己思考有哪些可能的输入情况。

注意:本题没有输入规定,所以你需要汇集所有的输入要求。


atoi要求:

该函数首先无视所有的空白符,直到找到第一个非空白符。 然后,从该字符开始,获取一个可选的初始加号或减号,后面跟尽可能多的数字,并将其解释为数值。

字符串可以在构成数值的字符之后包含其他的字符,这些字符将被忽略,并且对此函数的行为没有影响。

如果str中的非空白符的第一个序列不是有效的整数,或者如果没有这样的序列,因为str是空的或者它只包含空格字符,则不执行转换。

如果不能执行有效的转换,则返回零值。 如果正确的值超出可表示值的范围,则返回INT_MAX(2147483647)或INT_MIN(-2147483648)。


[解题思路]

挺水的一题,按照atoi的要求,纯模拟地做不会有什么问题,就是需要注意一些情况。

偷了个懒,直接用了c++的stringstream。其实,真的去写一下的话,还是挺有意义的,还是建议自己写一下。


[C++代码]

#include #include using namespace std;class Solution {public:int myAtoi(string str) {stringstream ss;int res;ss << str;ss >> res;return res;}};


0 0
原创粉丝点击