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.
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.
思路是很簡潔的,但正負號,空格包括中間和字符串的開始和結尾的字符,字符串溢出,整數表示的最大數和負數能表示的最小數。。。。
編程讓人變的更加嚴謹,目測還有很大的提升空間。
public static int atoi(String str) { BigInteger integer=new BigInteger("0"); if(str==null) return 0; str=str.trim(); if(str.equals("")) return 0; int len=str.length(); int flag=0; if(str.charAt(0)=='-') flag=-1; else if(str.charAt(0)=='+') flag=1; int i=0; if(flag!=0) i=1; if(str.charAt(i)>'9'||str.charAt(i)<'0') flag=-2; for(int j=i;j'9'||str.charAt(j)<'0') break; integer=integer.multiply(BigInteger.valueOf(10)).add(BigInteger.valueOf(str.charAt(j)-'0')); } if(flag==-2)return 0; if(flag==-1) { integer=integer.multiply(BigInteger.valueOf(-1)); if(integer.compareTo(BigInteger.valueOf(-2147483648))<0) return -2147483648; }else if(integer.compareTo(BigInteger.valueOf(2147483647))>0) { return 2147483647; } return integer.intValue(); }