|
1 | | -class ContestScanner{ |
| 1 | +class ContestScanner { |
2 | 2 | private final java.io.InputStream in; |
3 | 3 | private final byte[] buffer = new byte[1024]; |
4 | 4 | private int ptr = 0; |
5 | 5 | private int buflen = 0; |
| 6 | + |
| 7 | + private static final long LONG_MAX_TENTHS = 922337203685477580L; |
| 8 | + private static final int LONG_MAX_LAST_DIGIT = 7; |
| 9 | + private static final int LONG_MIN_LAST_DIGIT = 8; |
| 10 | + |
6 | 11 | public ContestScanner(java.io.InputStream in){ |
7 | 12 | this.in = in; |
8 | 13 | } |
@@ -59,10 +64,42 @@ public long nextLong() { |
59 | 64 | if (b < '0' || '9' < b) { |
60 | 65 | throw new NumberFormatException(); |
61 | 66 | } |
62 | | - while(true){ |
| 67 | + while (true) { |
63 | 68 | if ('0' <= b && b <= '9') { |
64 | | - n *= 10; |
65 | | - n += b - '0'; |
| 69 | + int digit = b - '0'; |
| 70 | + if (n >= LONG_MAX_TENTHS) { |
| 71 | + if (n == LONG_MAX_TENTHS) { |
| 72 | + if (minus) { |
| 73 | + if (digit <= LONG_MIN_LAST_DIGIT) { |
| 74 | + n = -n * 10 - digit; |
| 75 | + b = readByte(); |
| 76 | + if (!isPrintableChar(b)) { |
| 77 | + return n; |
| 78 | + } else if (b < '0' || '9' < b) { |
| 79 | + throw new NumberFormatException( |
| 80 | + String.format("%d%s... is not number", n, Character.toString(b)) |
| 81 | + ); |
| 82 | + } |
| 83 | + } |
| 84 | + } else { |
| 85 | + if (digit <= LONG_MAX_LAST_DIGIT) { |
| 86 | + n = n * 10 + digit; |
| 87 | + b = readByte(); |
| 88 | + if (!isPrintableChar(b)) { |
| 89 | + return n; |
| 90 | + } else if (b < '0' || '9' < b) { |
| 91 | + throw new NumberFormatException( |
| 92 | + String.format("%d%s... is not number", n, Character.toString(b)) |
| 93 | + ); |
| 94 | + } |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + throw new ArithmeticException( |
| 99 | + String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) |
| 100 | + ); |
| 101 | + } |
| 102 | + n = n * 10 + digit; |
66 | 103 | }else if(b == -1 || !isPrintableChar(b)){ |
67 | 104 | return minus ? -n : n; |
68 | 105 | }else{ |
|
0 commit comments