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
The
read
function will only be called once for each test case.
每次read4读到的字符放入一个数组里, 然后把数组里面的值拷贝到buffer内
concer case1: 在i = n - 1 时如果我们的read4 读了多个字符(长度len) , 那么我们存入buf数组中的个数应为Math.min(n - i, len)
case2: 如果len < 4 说明数组已经读完了 这时候返回的长度应该是Math.min(i + len, n)
concer case1: 在i = n - 1 时如果我们的read4 读了多个字符(长度len) , 那么我们存入buf数组中的个数应为Math.min(n - i, len)
case2: 如果len < 4 说明数组已经读完了 这时候返回的长度应该是Math.min(i + len, n)
public class Solution extends Reader4 { public int read(char[] buf, int n) { char[] tem = new char[4]; int index = 0; for (int i = 0; i < n; i+= 4) { int len = read4(tem); for (int j = 0; j < Math.min(len, n - i); j++) {//case1 buf[index++] = tem[j]; } if (len < 4) {//case 2 return Math.min(i + len, n); } }//如果循环内没有返回 说明读取字符数为4的倍数
return n; } }
没有评论:
发表评论