Advertisement
Guest User

Untitled

a guest
Dec 6th, 2017
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.00 KB | None | 0 0
  1. public static long parseLong(String s, int radix)
  2.               throws NumberFormatException
  3.     {
  4.         if (s == null) {
  5.             throw new NumberFormatException("null");
  6.         }
  7.  
  8.         if (radix < Character.MIN_RADIX) {
  9.             throw new NumberFormatException("radix " + radix +
  10.                                             " less than Character.MIN_RADIX");
  11.         }
  12.         if (radix > Character.MAX_RADIX) {
  13.             throw new NumberFormatException("radix " + radix +
  14.                                             " greater than Character.MAX_RADIX");
  15.         }
  16.  
  17.         boolean negative = false;
  18.         int i = 0, len = s.length();
  19.         long limit = -Long.MAX_VALUE;
  20.  
  21.         if (len > 0) {
  22.             char firstChar = s.charAt(0);
  23.             if (firstChar < '0') { // Possible leading "+" or "-"
  24.                 if (firstChar == '-') {
  25.                     negative = true;
  26.                     limit = Long.MIN_VALUE;
  27.                 } else if (firstChar != '+') {
  28.                     throw NumberFormatException.forInputString(s);
  29.                 }
  30.  
  31.                 if (len == 1) { // Cannot have lone "+" or "-"
  32.                     throw NumberFormatException.forInputString(s);
  33.                 }
  34.                 i++;
  35.             }
  36.             long multmin = limit / radix;
  37.             long result = 0;
  38.             while (i < len) {
  39.                 // Accumulating negatively avoids surprises near MAX_VALUE
  40.                 int digit = Character.digit(s.charAt(i++),radix);
  41.                 if (digit < 0 || result < multmin) {
  42.                     throw NumberFormatException.forInputString(s);
  43.                 }
  44.                 result *= radix;
  45.                 if (result < limit + digit) {
  46.                     throw NumberFormatException.forInputString(s);
  47.                 }
  48.                 result -= digit;
  49.             }
  50.             return negative ? result : -result;
  51.         } else {
  52.             throw NumberFormatException.forInputString(s);
  53.         }
  54.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement