【Leetcode】String to Integer(ATOI)

来源:互联网 发布:淘宝孕妇套装 编辑:程序博客网 时间:2024/06/03 21:57

【题目】

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.

【思路】

需要注意考虑的情况有很多很多,string的话可以是 空格 ,可以是其他的字符,需要进行判断。

string开始的时候可能有很多空字符,那么首先就是要去空字符,一直循环到不是“ “的时候停止。

然后出现的第一个有效的字符应该是符号字符。”+“, ”-“

出现字符的时候,要判断下一个紧接着是不是数字,如果不是数字,直接返回错,因为根本就不是一个正常的数字.

判断已有的结果是否已经达到了最大值/10, 或者等于最大值除以10,并且下一个数字>8,就根据正负号返回最大或者最小值,否则就继续添加下一个数字。

步骤 :

1. 去空字符

2. 符号字符

3. 判断溢出


最后返回带有符号的结果。


【代码】

public class Solution {    public int atoi(String str) {      final int INT_MAX=Integer.MAX_VALUE;final int INT_MIN=Integer.MIN_VALUE;  if(str.length() == 0)            return 0;        int i=0;        int flag = 1;        int tmp = 0;        while(str.charAt(i)==' ')            i++;                if(str.charAt(i) == '+'||str.charAt(i) == '-'){         if(!(str.charAt(i+1) >= '0' && str.charAt(i+1) <= '9')) return 0;         if(str.charAt(i) == '-')        {            flag = -1;        }         i++;        }        while (i<str.length()&&str.charAt(i) >= '0' && str.charAt(i) <= '9') {            if (tmp >  INT_MAX / 10 || (tmp == INT_MAX / 10 && str.charAt(i) - '0' > 7)) {                if (flag == 1) return INT_MAX;                else return INT_MIN;            }            tmp  = 10 * tmp + (str.charAt(i++) - '0');        }        return tmp*flag;        }}


0 0
原创粉丝点击