Atoi is a function that converts a string to an integer, how does it work with Java? Looks simple, traps a lot, in the Leetcode website, this function can write completely correct probability only 14%.
atoi's need Is this:
If there are spaces in front, you need to exclude spaces;
If the first string is the + number, it is considered a positive number, if it is a negative, the
After the character is not a number, then return 0, if it is a number, return the actual number. The conversion ends when a character that is not a number is encountered.
public class Solution {
public int atoi (String str) {
Be careful here, you need to judge the validity.
if (Str==null | | str.length () = = 0)
{
return 0;
}
int nlen = Str.length ();
Double sum = 0;
int sign = 1;
int j = 0;
Exclude spaces
while (Str.charat (j) = = ")
j + +;
Judging positive and negative numbers
if (Str.charat (j) = = ' + ')
{
sign = 1;
j + +;
}else if (Str.charat (j) = = '-')
{
sign =-1;
j + +;
}
for (int i=j;i<nlen;i++)
{
Char current = Str.charat (i);
if (current >= ' 0 ' && <= ' 9 ')
{
sum = sum*10 + (int) (current-' 0 ');
}
Else
{
Break //hit non-digit, exit conversion
}
}
sum = sum*sign;
Be careful here, you need to judge the range.
if (Sum > Integer.max_value) {
sum = Integer.max_value;
} else if (Sum < Integer.min_value) {
sum = Integer.min_value;
}
return (int) sum;
}
}
Java implementation of Atoi