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 public class Solution extends Reader4 {
 2 
 3     public int read(char[] buf, int n) {
 4         char[] buffer = new char[4];
 5         int readBytes = 0;
 6         boolean eof = false;
 7 
 8         while(!eof && readBytes < n) {
 9             int sz = read4(buffer);
10             if(sz < 4) {
11                 eof = true;
12             }
13 
14             int bytes = Math.min(n-readBytes, sz);
15             // buffer:src
16             // buf:dst
17             // readBytes:destPos
18             // bytes:length
19             System.arraycopy(buffer, buf, readBytes, bytes);
20             readBytes = readBytes + bytes;
21         }
22 
23         return readBytes;
24     }
25 }

猜你喜欢

转载自www.cnblogs.com/wylwyl/p/10403177.html
今日推荐