首页 > 代码库 > 157 Read N Characters Given Read4
157 Read N Characters Given Read4
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.
说明:1. read4(char * buf)的这个buf起初是空的,然后read4读出来的东西存在这个buf里;
2. read函数的buf是destination, 是我们需要往里面依次写通过read4读出来的东西
* @param buf Destination buffer,我后来理解这个应该是个足够大的buffer,需要将读到的file放到这个buffer里面去
* @param n Maximum number of characters to read,想要读n个char,但是有可能读不到那么多,因为有可能n比文件的size大
* @return The number of characters read,实际读到的char数,小于等于n
由于不知道文件的大小,所以只能一次一次用4个char的buffer用read4去读,存在以下两种结束方式(假设文件大小为size):
1. n >> size, 比如n = 50, size = 23, 最后一次读的大小为<4, 下一次就不读了,然后把这一次读的char数oneRead赋给目标buf
至于n = 50, size = 20, 最后一次读到0个,不会进行赋值,下一次也不读了
2. n << size,比如n = 23, size = 50, read4每次会读满4个,但是我们只取3个,取零头的方法是int actRead = Math.min(n-haveRead, oneRead); 下一次OneRead+haveRead>n, 也就停止了
想清楚了这些,就可以写了
/* 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[] buffer = new char[4]; int haveRead = 0; boolean lessthan4 = false; while (!lessthan4 && haveRead < n) { int oneRead = read4(buffer); if (oneRead < 4) lessthan4 = true; int actRead = Math.min(n-haveRead, oneRead); while (int i=0; i<actRead; i++) { buf[haveRead+i] = buffer[i]; } haveRead += actRead; } return haveRead; } }
157 Read N Characters Given Read4