Read N Characters Given Read4 I & II

时间:2023-03-09 03:46:39
Read N Characters Given Read4 I & II

The API: int read4(char *buf) reads 4 characters at a time from a file.

The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.

By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.

Note: The read function may be called only once.

 public class Solution extends Reader4 {
public int read(char[] buf, int n) {
int index = ;
char[] tmp = new char[]; // temp buffer while (index < n) {
int count = read4(tmp);
count = Math.min(count, n - index);
for (int i = ; i < count; i++) {
buf[index++] = tmp[i];
}
if (count < ) {
return index;
}
}
return index;
}
}
 public class Solution extends Reader4 {
public int read(char[] buf, int n) {
boolean eof = false;
int charsRead = ;
char[] buf4 = new char[]; while (!eof && charsRead < n) {
int size = read4(buf4);
if (size < ) {
eof = true;
} if (charsRead + size > n) {
size = n - charsRead;
} System.arraycopy(buf4, , buf, charsRead, size);
charsRead += size;
}
return charsRead;
}
}

Read N Characters Given Read4 II - Call multiple times

The API: int read4(char *buf) reads 4 characters at a time from a file.

The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.

By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.

Note: The read function may be called multiple times.

分析:

 public class Solution extends Reader4 {
char[] buffer = new char[];
int bufferSize = , prevIndex = ; public int read(char[] buf, int n) {
int index = ;
while (index < n) {
if (prevIndex < bufferSize) {
buf[index++] = buffer[prevIndex++];
} else {
bufferSize = read4(buffer);
prevIndex = ;
if (bufferSize == ) { break; }
}
}
return index;
}
}
 public class Solution extends Reader4 {
private char[] buffer = new char[];
int offset = , bufsize = ; public int read(char[] buf, int n) {
int readBytes = ;
boolean eof = false;
while (!eof && readBytes < n) {
int sz = (bufsize > ) ? bufsize : read4(buffer);
if (bufsize == && sz < ) eof = true;
int bytes = Math.min(n - readBytes, sz);
System.arraycopy(buffer, offset, buf, readBytes, bytes);
offset = (offset + bytes) % ;
bufsize = sz - bytes;
readBytes += bytes;
}
return readBytes;
}
}