Skip to content

Instantly share code, notes, and snippets.

@HDegano
Last active August 29, 2015 14:22
Show Gist options
  • Save HDegano/4a40545a6c3930b7bf7f to your computer and use it in GitHub Desktop.
Save HDegano/4a40545a6c3930b7bf7f to your computer and use it in GitHub Desktop.
string to int
//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