Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please don't see below and ask yourself what is the possible input cases.
Notes: It is intended for the problem to be specified vaguely (ie, no given input specs). You is responsible to gather all the input requirements up front.
Test instructions: Converts a string to an integer type. The feeling is not very simple, after many changes, finally accepted!!!
There are many issues to consider, first of all the processing of non-numeric characters encountered in string conversion, the string exceeds the maximum integer type and the minimum integer is how to handle.
The open question encounters the space, uses the trim () to go the space.
+,-can only be the first place after the space is removed.
A non-numeric character is encountered in the middle, directly returning the previous character, judging whether it is valid, and converting to an integral type.
The code is as follows:
public int myatoi (String str) { if (str==null) return 0; Str=str.trim ();//go to space int len=str.length (); if (len==0) return 0; Char signal= ' + '; int singalnum=0; int i=0; Char Ch=str.charat (i); Double result=0; while (I<len) { Ch=str.charat (i); if (ch== '-' | | ch== ' + ')//judgment symbol {if (i!=0) return 0;//if the symbol is not in the first place, return 0 if (ch== '-') signal= '-'; } else if (ch>= ' 0 ' &&ch<= ' 9 ') { result=result*10+ (Str.charat (i)-' 0 ');//Handle Digital }else if (ch < ' 0 ' | | Ch> ' 9 ')//encounters a non-numeric character, jumps out of the loop, computes only the valid numeric character {break, before the non-digit) ; i++; } if (signal== '-') Result=-1*result; if (result>integer.max_value) return integer.max_value; if (result<integer.min_value) return integer.min_value; return (int) result;
[JAVA] LeetCode8 String to Integer (atoi)