leetcode之路008 String to Integer (atoi)

来源:互联网 发布:淘宝的旗舰店可信吗 编辑:程序博客网 时间:2024/04/30 01:45


题目大意:实现atoi的功能,把一个字符串转化为整数。

首先的考虑所有的情况,有以下:

1、字符串为空,返回0;

2、字符串中含有‘ ’空格字符,则需要跳过所有空格;

3、考虑符号问题,‘-’和‘+’,最开始自己就没想到‘+’也要考虑;

4、然后必须为数字0-9,如果不为数字,则返回前面已经确定的值。例:“-123a87”,返回的是-123,而不是直接返回错误的值,这这也是最开始完全没想到的,以为直接返回0即可。

5、超出范围问题,超过INT_MAX则返回INT_MAX,小于INT_MIN则返回INT_MIN。刚开始想到要考虑此问题,但以为是返回0,因为也出错。


看似简单的一个题,需要考虑的情况太多,很容易出错,这也是此题ac率只有12%的原因,但题目不说清楚各种情况的返回值值得吐槽。

下面是ac的代码,时间12ms:

class Solution {public:    int myAtoi(string str) {int flag=0;long long resu=0;int j=0;if(str.length()==0)return 0;while(str[j]==' ')++j;str=str.substr(j,str.length()-j);if(str[0]=='-'){flag=1;str=str.substr(1,str.length()-1);}else if(str[0]=='+')str=str.substr(1,str.length()-1);for(int i=0;i<str.length();++i){if(str[i]>='0'&&str[i]<='9'&&resu<INT_MAX)resu=10*resu+(str[i]-'0');elsebreak;}if(flag)resu=flag?-resu:resu;  if(resu>INT_MAX)resu=INT_MAX;else if(resu<INT_MIN)resu=INT_MIN;return resu;    }};


讨论区更简单的实现代码如下:

int myAtoi(string str) {    long result = 0;    int indicator = 1;    for(int i = 0; i<str.size();)    {        i = str.find_first_not_of(' ');        if(str[i] == '-' || str[i] == '+')            indicator = (str[i++] == '-')? -1 : 1;        while('0'<= str[i] && str[i] <= '9')         {            result = result*10 + (str[i++]-'0');            if(result*indicator >= INT_MAX) return INT_MAX;            if(result*indicator <= INT_MIN) return INT_MIN;                        }        return result*indicator;    }}

2016.09.04更新 JAVA代码

public class Solution {    public int myAtoi(String str) {        long res = 0;        boolean flag = true;        str = str.trim();        for(int i = 0; i < str.length(); i++) {            char ch = str.charAt(i);            if(i == 0 && (ch == '+' || ch == '-')) {                flag = ch == '+' ? true : false;            } else if(ch >= '0' && ch <= '9') {                res = 10 * res + (ch - '0');            } else {            break;            }            if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) {            break;            }        }        res = flag ? res : -1 * res;        if(res > (long)Integer.MAX_VALUE) {            res = Integer.MAX_VALUE;        } else if(res < (long)Integer.MIN_VALUE) {        res = Integer.MIN_VALUE;        }        return (int)res;    }}



0 0
原创粉丝点击