Created
December 19, 2014 15:39
-
-
Save wangchauyan/3fce5f852584970cc36c to your computer and use it in GitHub Desktop.
String to Integer
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
package wcy.leetcode.gist; | |
/** | |
* Created by ChauyanWang on 12/19/14. | |
*/ | |
public class string2Int { | |
public int atoi(String number) { | |
if (number == null || number.length() == 0) return 0; | |
double result = 0; | |
int startIndex = 0; | |
boolean isNegative = false; | |
// skip header / tail space char | |
number = number.trim(); | |
if(number.charAt(0) == '+') | |
startIndex ++ ; | |
else if (number.charAt(0) == '-'){ | |
isNegative = true; | |
startIndex ++ ; | |
} | |
while(startIndex < number.length() && | |
number.charAt(startIndex) >= '0' && | |
number.charAt(startIndex) <= '9') { | |
result = result * 10 + (number.charAt(startIndex) - '0'); | |
startIndex ++; | |
} | |
if(isNegative) result = -result; | |
if(result > Integer.MAX_VALUE) return Integer.MAX_VALUE; | |
else 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