Title Description: Convert String to Integer value original description: 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.
Thinking Analysis:
- First judgment is empty, return 0
- Consider the space above, use trim () to remove, and then determine whether the length is 0, yes, return 0
- Determine if the first character is A + and-, set the variable sign record.
- Loop gets the number of the string, considering that there is a non-digit in the string, to exit, to retain the preceding number
- Overflow returns the maximum and minimum values for an integer, considering overflow conditions
Code implementation:
Public class solution { Public intMyatoi (StringStr) {//To determine the null value first if(Str==NULL){return 0; }//The case of removing spaces Str=Str. Trim ();if(Str. Length () = =0){return 0; }intSign =1;int Index=0;if(Str. CharAt (Index) ==' + '){Index++; }Else if(Str. CharAt (Index) =='-'){Index++; Sign =-1; }//Get digital part, encounter overflow and non-digital exit LongNumber =0; for(;Index<Str. Length ();Index++){if(Str. CharAt (Index) <' 0 '||Str. CharAt (Index) >' 9 '){ Break; } number = number *Ten+ (Str. CharAt (Index) -' 0 ');if(Number >= Integer.max_value) { Break; } }if(number * Sign >= integer.max_value) {returnInteger.max_value; }if(number * Sign <= integer.min_value) {returnInteger.min_value; }return(int) Number*sign; }}
My QR code is as follows, welcome to exchange discussion
You are welcome to pay attention to the "It question summary" subscription number. Every day to push the classic face test and interview tips, are dry! The QR code of the subscription number is as follows:
[Leetcode] Classic algorithmic question-String to Integer (atoi)