157 Read N Characters Given Read4 – Easy
Problem:
Thoughts
Solutions:
/* 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) {
int offset = 0;
char[] buf4 = new char[4];
int buf4index = 0;
int buf4size = 0;
while(offset < n) {
if (buf4index >= buf4size) {
buf4size = read4(buf4);
buf4index = 0;
if (buf4size == 0) {
break;
}
}
buf[offset] = buf4[buf4index];
offset ++;
buf4index ++;
}
return offset;
}
}Previous156 Binary Tree Upside Down – MediumNext158 Read N Characters Given Read4 II – Call multiple times Add to List QuestionEditorial Solution –
Last updated