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 will only be called once for each test case.
read4(char[] buf)指的是读取4个数,存储在buf中,然后返回成功读取的数目,如果不够四个,那么就返回剩余数目的字符。
实现的read(char[] buf, int n)功能类似,只不过将4改为了n,需要输入而已。(这里一个例子只会读取一次read)
刚开始做的时候理解错了,以为是读取buf中的字符,导致提交失败。
方法是:先读取n/4次read4,如果期间有出现了不等于4的情况,那么返回结果。
然后读取最后一次,需要判断的是:1、如果刚好读完了,直接返回结果
2、判断n-result和读取数目num的大小,选择小的,读取并返回数目。
/* 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) { if (n < 1){ return 0; } int time = n / 4; int result = 0; char[] chars = new char[4]; for (int i = 0; i < time; i++){ int num = read4(chars); for (int j = 0; j < num; j++){ buf[i * 4 + j] = chars[j]; } if (num != 4){ result += num; return result; } else { result += 4; } } if (n - result == 0){ return result; } int num = read4(chars); for (int i = 0; i < Math.min(n - result, num); i++){ buf[result + i] = chars[i]; } result += Math.min(n - result, num); return result; } }