Skip to content

Commit 543d427

Browse files
authored
Update Read N characters Given Read4.java
1 parent 5be1437 commit 543d427

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed
Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/**
22
* The read4 API is defined in the parent class Reader4.
3-
* int read4(char[] buf);
3+
* int read4(char[] buf4);
44
*/
55

66
public class Solution extends Reader4 {
@@ -10,17 +10,19 @@ public class Solution extends Reader4 {
1010
* @return The number of actual characters read
1111
*/
1212
public int read(char[] buf, int n) {
13-
boolean endOfFile = false;
14-
int totalLength = 0;
15-
char[] temp = new char[4];
16-
while (!endOfFile && totalLength < n) {
17-
int count = read4(temp);
18-
endOfFile = count < 4;
19-
count = Math.min(count, n - totalLength);
20-
for (int i = 0; i < count; i++) {
21-
buf[totalLength++] = temp[i];
13+
int copied = 0;
14+
int readLength = 4;
15+
char[] buf4 = new char[4];
16+
while (copied < n && readLength == 4) {
17+
readLength = read4(buf4);
18+
for (int i = 0; i < readLength; i++) {
19+
if (copied == n) {
20+
return copied;
21+
}
22+
buf[copied] = buf4[i];
23+
copied++;
2224
}
2325
}
24-
return totalLength;
26+
return copied;
2527
}
2628
}

0 commit comments

Comments
 (0)