forked from huailian123/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path158_readN_givenRead4_2.java
More file actions
37 lines (31 loc) · 1002 Bytes
/
Copy path158_readN_givenRead4_2.java
File metadata and controls
37 lines (31 loc) · 1002 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* The read4 API is defined in the parent class Reader4.
int read4(char[] buf); */
public class Solution extends Reader4 {
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
char[] buffer = new char[4];
int buffSize = 0;
int offset = 0;
public int read(char[] buf, int n) {
int readBytes = 0;
int bytes = 0;
boolean eof = false;
while(!eof && readBytes < n){
if(buffSize == 0){
buffSize = read4(buffer);
if(buffSize < 4) eof = true;
}
bytes = Math.min(buffSize, n-readBytes);
for(int i = 0; i < bytes; i++){
buf[readBytes+i] = buffer[offset+i];
}
readBytes += bytes;
offset = (offset+bytes)%4;
buffSize -= bytes;
}
return readBytes;
}
}