LeetCode 8. String to Integer (atoi)

来源:互联网 发布:windows系统快捷键设置 编辑:程序博客网 时间:2024/06/15 23:59

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.


这个题真的是很难考虑到那么多种奇葩的情况,靠debug来刷新三观。

public class Solution {    public int myAtoi(String str) {        if (str.length()==0||str==null){            return 0;        }        for(int i=0;i<str.length();i++){            if(str.charAt(i)==' '){                continue;            }            str = str.substring(i);            break;        }        int flag = 1;        if(str.charAt(0)=='+'){            flag = 1;            str = str.substring(1);        }        else if(str.charAt(0)=='-'){            flag = -1;            str = str.substring(1);        }        long ans = 0;        int len = str.length();        for(int i=0;i<len;i++){            if(str.charAt(i)>='0'&&str.charAt(i)<='9'){                ans = ans*10+Character.getNumericValue(str.charAt(i));                if(flag*ans>Integer.MAX_VALUE){                    return Integer.MAX_VALUE;                }                if(flag*ans<Integer.MIN_VALUE){                    return Integer.MIN_VALUE;                }            }            if((str.charAt(i)<'0'||str.charAt(i)>'9')){                break;            }        }        return (int)ans*flag;    }}
注意考虑空格、正负号、溢出等等情况

0 0
原创粉丝点击