leetcode String to Integer (atoi)(Java)

来源:互联网 发布:linux yum 编辑:程序博客网 时间:2024/05/29 09:05

题目链接:点击打开链接

类型:字符串处理,边界处理

解法:

public class Solution {    public int myAtoi(String str) {        if (str == null || str.length() < 1 )        return 0;        str = str.trim();        int len = str.length();        long result = 0;        boolean negative = false;                int i = 0;        if (str.charAt(0) == '-')        {        negative = true;        ++i;        }        else if (str.charAt(0) == '+')        {        ++i;        }                while ((i < len) && (str.charAt(i) >= '0') && (str.charAt(i) <= '9'))        {        result = result * 10 + (str.charAt(i) - '0');            if (result > Integer.MAX_VALUE)               return (negative)?(Integer.MIN_VALUE):(Integer.MAX_VALUE);        ++i;        }                if ((i == 1 && result == 0) || i == 0)        return 0;                if (negative == true)        result = -result;                return (int)result;    }}