leetCode 8. String to Integer (atoi) (字符串转整形) 解题思路和方法

来源:互联网 发布:iphone6手机壳淘宝 编辑:程序博客网 时间:2024/06/05 05:01

问题:

String to Integer (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.


思路:此题不算难,但是最无可忍受的是出题方没有把规则告诉我们,所以这题怎么理解规则成了关键,我只能在不断试错中一步步走出正确的代码。

ps:这题通过率不高完全是出题方的恶意。

代码如下:

    public int myAtoi(String str) {    int max = Integer.MAX_VALUE;    int min = Integer.MIN_VALUE;    //首位数字是否出现        boolean isFirstNum = false;        String s = "";        for(int i = 0; i < str.length();i++){        //只有数字前面的字符为空才接受,否则直接跳出循环返回0            if((str.charAt(i) >= '0' && str.charAt(i) <= '9') || str.charAt(i) == '+' || str.charAt(i) == '-'){                isFirstNum = true;//标记出现                s += str.charAt(i);//保存字符            }else{                if(str.charAt(i) != ' '){                    break;//如果字符不为数字,也非空,直接结束                }else{                //如果为空,但是已经出现了数字,也结束                if(isFirstNum)                break;                }            }        }                if(s.length() > 0){            if(s.length() == 1 && (s.charAt(0) == '+' || s.charAt(0) == '-') ){            //长度只有1且为符号的返回0            }else{                long x = 0;                try{                //如果s长度超过14,则肯定超出int范围,分情况返回max或min                if(s.length() > 14){                        if(s.charAt(0) == '-'){                            return min;                        }else{                            return max;                        }                    }                //转成long,大于max的取max,小于min的取min                    x = Long.parseLong(s);                    x = x > max? max:x;                    x = x < min ? min:x;                    return (int) x;                }                catch(Exception e){                    //转型出错返回0                }            }        }        return 0;    }


0 0