Leetcode_8_String to Integer (atoi), leetcodeatoi
Description:
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 your 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 your numerical digits as possible, and interprets them as a numerical value.
The string can contain in 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 saved med.
If no valid conversion cocould be specified med, 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.
Ideas:
The idea is concise, but the plus and minus signs, spaces include the start and end characters of the middle and string, the string overflows, integer represents the maximum number and negative number represents the minimum number ....
Programming makes people more rigorous, and there is still much room for improvement in visual testing.
Code:
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<len;j++) { if(str.charAt(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(); }
Result:
Two lines in The Godfather: female and children are not careful, but men are not!
Consider an accident as an insult to personal dignity.