Read N Characters Given Read4
https://leetcode.com/problems/read-n-characters-given-read4/description/
Thoughts
Code
/* 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
*/
public int read(char[] buf, int n) {
char[] inBuf = new char[4];
int index = 0;
while (index < n) {
int count = read4(inBuf);
if (count == 0) {
break;
}
for (int i = 0; i < count && index < n; i++) {
buf[index++] = inBuf[i];
}
}
return index;
}
}Analysis
Last updated