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.

链接: http://leetcode.com/problems/read-n-characters-given-read4/

2/19/2017, Java,答案抄的

思路,每次尝试读4个到临时temp buffer中,然后按照n来赋值到buf。

不要直接read4读到buf中

 1 public class Solution extends Reader4 {
 2     /**
 3      * @param buf Destination buffer
 4      * @param n   Maximum number of characters to read
 5      * @return    The number of characters read
 6      */
 7     public int read(char[] buf, int n) {
 8         char[] temp = new char[4];
 9         int totalSize = 0;
10         int size = 0;
11         
12         while((size = read4(temp)) > 0) {
13             for (int i = 0; i < size && totalSize < n; i++) {
14                 buf[totalSize++] = temp[i];
15             }
16             if (totalSize >= n) break;
17         }
18         return totalSize;
19     }
20 }

 

posted @ 2017-02-19 23:50  panini  阅读(195)  评论(0编辑  收藏  举报