8. String to Integer (atoi)

来源:互联网 发布:python 写入环境变量 编辑:程序博客网 时间:2024/06/05 16:22

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 aconst char * argument, please click the reload button to reset your code definition.

spoilers alert... click to show requirements for atoi.

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.


这道题可以说是很变态了!!

1.如果开头是空格,需要去掉

2.如果是‘+’‘-’需要根据它判别正负

3.如果出现非法字符就停止

4.如果超过integer范围,返回0  这里我用long存储结果,但是还有可能超过long的范围,所以每一次更新结果的时候都判断是否溢出,就可以防止long溢出。

5.如果只有空格 返回0

6.判断过符号之后记得i++

7.记得str.charAt(i)>='0'&&str.charAt(i)<='9' 大于等于 小于等于

 public static int myAtoi(String str) {        long res = 0;        if(str=="")        return 0;        int minus = 1;        char[] arr = str.toCharArray();        int i =0;        for(;i<arr.length;i++){        if(arr[i]!=' ')                break;        }        if(i==arr.length)        return 0;        if(arr[i]=='-'||arr[i]=='+'){                        minus=(arr[i]=='-')?-1:1;                i++;        }        for(;i<arr.length;i++){        if(arr[i]<='9'&&arr[i]>='0')        res = res*10 +arr[i]-'0';                else         break;                if(res>Integer.MAX_VALUE||res<Integer.MIN_VALUE)            return minus==-1?Integer.MIN_VALUE:Integer.MAX_VALUE;        }               res = res*minus;                       return (int)res;    }

方法二:利用java string自带的函数trim去掉前面的空格。trim函数可以去掉字符串靠头和结尾的空格。

另外还有一个函数Character.isDigit(c)可以判断字符是否是数字。

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


原创粉丝点击