I have been solving problems on Timus Online Judge. In the beginning, I didn't worry much about I/O operations, so I just took some code from the internet and focused more on the logic. But after going through the helper class that I was using, I created my own class.
This is the original stuff:
import java.io.InputStream;
public class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() throws Exception {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() throws Exception {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() throws Exception {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
This is what I have written now:
import java.io.IOException;
public class IOUtils {
public static String readString() throws Exception {
int c = System.in.read();
while (isSpaceChar(c))
c = System.in.read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = System.in.read();
} while (!isSpaceChar(c));
return res.toString();
}
public static int readInt() throws IOException {
int i = 0;
int c = System.in.read();
while (isSpaceChar(c))
c = System.in.read();
int sign = 1;
if (c == '-') {
sign = -1;
c = System.in.read();
}
do {
i = i * 10 + c - '0';
c = System.in.read();
} while (!isSpaceChar(c));
return i * sign;
}
public static int readPositiveInt() throws IOException {
int i = 0;
int c = System.in.read();
while (isSpaceChar(c))
c = System.in.read();
do {
i = i * 10 + c - '0';
c = System.in.read();
} while (!isSpaceChar(c));
return i;
}
private static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == -1;
}
}
Is my code any better than the original? Could someone look into it and let me know about the performance and the pitfalls?