Created
February 12, 2014 21:44
-
-
Save rayjcwu/8965151 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 class StringToLong { | |
| public long stringToLong(String s) { | |
| return stringToLong(s, true, true, true); | |
| } | |
| public long stringToLong( | |
| String s, | |
| boolean allowHeadingTailingSpaces, // allow spaces in the begin/end of string | |
| boolean allowNonDigit, // allow non digit char in the end, will only parse all digits | |
| boolean allowSaturate // will return Long.MAX_VALUE/Long.MIN_VALUE instead of throw exception | |
| ) { | |
| String str = s.trim(); | |
| if (!allowHeadingTailingSpaces && str.length() != s.length() ) { | |
| throw new NumberFormatException(String.format("%s has heading/tailing spaces in the string", s)); | |
| } | |
| final int N = str.length(); | |
| long val = 0; | |
| boolean neg = false; | |
| int i = 0; | |
| if (i < N && str.charAt(0) == '-') { | |
| neg = true; | |
| i++; | |
| } | |
| for (; i < N; i++) { | |
| char c = str.charAt(i); | |
| if (!isDigit(c)) { | |
| if(!allowNonDigit) { | |
| throw new NumberFormatException(String.format("%s has non-digit character", s)); | |
| } else { | |
| break; | |
| } | |
| } | |
| int charVal = ctoi(c); | |
| // check for overflow | |
| // long: -9223372036854775808 ~ 9223372036854775807 | |
| if ((!neg && val >= 922337203685477580L && charVal > 7) || | |
| ( neg && val <= -922337203685477580L && charVal > 8)) { | |
| if (!allowSaturate) { | |
| throw new NumberFormatException(String.format("%s is out of range", s)); | |
| } else { | |
| val = (neg) ? Long.MIN_VALUE : Long.MAX_VALUE; | |
| break; | |
| } | |
| } | |
| val = 10 * val + ((neg) ? -charVal : charVal); | |
| } | |
| return val; | |
| } | |
| private boolean isDigit(char c) { | |
| return (c >= '0') && (c <= '9'); | |
| } | |
| private int ctoi(char c) { | |
| return c - '0'; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment