[LeetCode] String to Integer (atoi)

来源:互联网 发布:暮光女 出柜 知乎 编辑:程序博客网 时间:2024/06/07 13:29

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.

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