Topic:
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-problem to be specified vaguely (ie, no given input specs). You is responsible to gather all the input requirements up front.
Requirements for Atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, the starting from this character, takes a optional initial plus or minus sign followed by as many numerical digits as P Ossible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which is ignored and has no Effe CT on the behavior of this function.
If the first sequence of non-whitespace characters in STR isn't a valid integral number, or if no such sequence exists be Cause 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 Returne D.
Ideas:
The topic is to convert string strings into integer data, similar to the Atoi function in C + + library, the key to solve this problem lies in two aspects: (1) The legal judgment of the string format (2) The overflow judgment of the conversion result
public class Solution {public int myatoi (String str) {Str=str.trim (); Char[] Arr=str.tochararray (); if (arr.length==0) {return 0; } int i=0; Boolean symbol=true; if (arr[i]== '-') {symbol=false; i++; }else if (arr[i]== ' + ') {i++; } long Max_value=integer.max_value; Long Min_value=integer.min_value; Long num=0; for (int j=i;j<arr.length;j++) {if (arr[j]>= ' 0 ' &&arr[j]<= ' 9 ') {num=num*10+arr[j]- ' 0 '; }else{break; } if (!symbol&& (0-num<min_value)) {return integer.min_value; }else if (symbol&& (Num>max_value)) {return integer.max_value; }} return symbol?new long (num). Intvalue (): New Long (0-num). Intvalue (); }}
"Leetcode" 8. String to Integer (atoi) string to integer