Skip to content

Instantly share code, notes, and snippets.

@sopherwang
Created September 14, 2014 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sopherwang/d2c2a68ed80ecb8093b7 to your computer and use it in GitHub Desktop.
Save sopherwang/d2c2a68ed80ecb8093b7 to your computer and use it in GitHub Desktop.
String to Integer (atoi)
public int atoi(String str) {
//1. space
//2. +/-
//3. invalid character
//4. null
//5. MAX_INT and MIN_INT
if (str == null || str.length() == 0)
return 0;
str = str.trim();
char flag = '+';
int i = 0;
if (str.charAt(i) == '-')
{
flag = '-';
i++;
}
else if (str.charAt(i) == '+')
i++;
double result = 0;
while (i < str.length() && str.charAt(i) <= '9' && str.charAt(i) >= '0')
{
result = result * 10 + (str.charAt(i) - '0');
i++;
}
if (flag == '-')
{
result = -result;
}
if (result > Integer.MAX_VALUE)
{
return Integer.MAX_VALUE;
}
if (result < Integer.MIN_VALUE)
{
return Integer.MIN_VALUE;
}
return (int) result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment