Last active
August 29, 2015 14:22
-
-
Save HDegano/4a40545a6c3930b7bf7f to your computer and use it in GitHub Desktop.
string to int
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
//From OJ handbook | |
public class StringToint{ | |
public int atio(String str){ | |
int i = 0; | |
int n = str.length(); | |
while(i < n && Character.isWhiteSpace(str.charAt(i))) i++; | |
int sign = 1; | |
if(i < n && str.charAt(i) == "+") i++; | |
else if(i < n && str.charAt(i) == "-") { | |
i++; | |
sign = -1; | |
} | |
int num = 0; | |
while(i < n && Character.isDigit(str.charAt(i))){ | |
int digit = Character.getNumericValue(str.charAt(i)); | |
if(num > maxDiv10 || num == maxDiv10 && digit >= 8){ //this takes care of the MIN_VAL edge case | |
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; | |
} | |
num = num * 10 + digit; | |
i++; | |
} | |
return sign * num; | |
} | |
private static final maxDiv10 = Integer.MAX_VALUE / 10; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment