Skip to content

Commit fc06289

Browse files
committed
fix NASU41#59
1 parent 0103480 commit fc06289

1 file changed

Lines changed: 52 additions & 4 deletions

File tree

‎ContestIO/ContestScanner.java‎

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,16 @@
1-
class ContestScanner{
1+
import java.io.IOException;
2+
import java.io.UncheckedIOException;
3+
4+
class ContestScanner implements AutoCloseable {
25
private final java.io.InputStream in;
36
private final byte[] buffer = new byte[1024];
47
private int ptr = 0;
58
private int buflen = 0;
9+
10+
private static final long LONG_MAX_TENTHS = 922337203685477580L;
11+
private static final int LONG_MAX_LAST_DIGIT = 7;
12+
private static final int LONG_MIN_LAST_DIGIT = 8;
13+
614
public ContestScanner(java.io.InputStream in){
715
this.in = in;
816
}
@@ -59,10 +67,42 @@ public long nextLong() {
5967
if (b < '0' || '9' < b) {
6068
throw new NumberFormatException();
6169
}
62-
while(true){
70+
while (true) {
6371
if ('0' <= b && b <= '9') {
64-
n *= 10;
65-
n += b - '0';
72+
int digit = b - '0';
73+
if (n >= LONG_MAX_TENTHS) {
74+
if (n == LONG_MAX_TENTHS) {
75+
if (minus) {
76+
if (digit <= LONG_MIN_LAST_DIGIT) {
77+
n = -n * 10 - digit;
78+
b = readByte();
79+
if (!isPrintableChar(b)) {
80+
return n;
81+
} else if (b < '0' || '9' < b) {
82+
throw new NumberFormatException(
83+
String.format("%d%s... is not number", n, Character.toString(b))
84+
);
85+
}
86+
}
87+
} else {
88+
if (digit <= LONG_MAX_LAST_DIGIT) {
89+
n = n * 10 + digit;
90+
b = readByte();
91+
if (!isPrintableChar(b)) {
92+
return n;
93+
} else if (b < '0' || '9' < b) {
94+
throw new NumberFormatException(
95+
String.format("%d%s... is not number", n, Character.toString(b))
96+
);
97+
}
98+
}
99+
}
100+
}
101+
throw new ArithmeticException(
102+
String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit)
103+
);
104+
}
105+
n = n * 10 + digit;
66106
}else if(b == -1 || !isPrintableChar(b)){
67107
return minus ? -n : n;
68108
}else{
@@ -143,4 +183,12 @@ public char[][] nextCharMatrix(int height, int width){
143183
}
144184
return mat;
145185
}
186+
@Override
187+
public void close() {
188+
try {
189+
in.close();
190+
} catch (IOException e) {
191+
throw new UncheckedIOException(e);
192+
}
193+
}
146194
}

0 commit comments

Comments
 (0)