Created
September 14, 2014 22:10
-
-
Save sopherwang/d2c2a68ed80ecb8093b7 to your computer and use it in GitHub Desktop.
String to Integer (atoi)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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