Skip to content

Commit b9de858

Browse files
authored
Merge pull request #60 from suisen-cp/master
fix #59: ContestScanner#nextLong does not detect overflow
2 parents 0103480 + 69adbaa commit b9de858

File tree

1 file changed

+41
-4
lines changed

1 file changed

+41
-4
lines changed

ContestIO/ContestScanner.java

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
1-
class ContestScanner{
1+
class ContestScanner {
22
private final java.io.InputStream in;
33
private final byte[] buffer = new byte[1024];
44
private int ptr = 0;
55
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+
611
public ContestScanner(java.io.InputStream in){
712
this.in = in;
813
}
@@ -59,10 +64,42 @@ public long nextLong() {
5964
if (b < '0' || '9' < b) {
6065
throw new NumberFormatException();
6166
}
62-
while(true){
67+
while (true) {
6368
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;
66103
}else if(b == -1 || !isPrintableChar(b)){
67104
return minus ? -n : n;
68105
}else{

0 commit comments

Comments
 (0)