[LeetCode] Read N Characters Given Read4 I & II

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 // Forward declaration of the read4 API.
 2 int read4(char *buf);
 3 
 4 class Solution {
 5 public:
 6     /**
 7      * @param buf Destination buffer
 8      * @param n   Maximum number of characters to read
 9      * @return    The number of characters read
10      */
11     int read(char *buf, int n) {
12         char tmp[4];
13         int idx = 0, cnt4;
14         while (idx < n) {
15             cnt4 = read4(tmp);
16             for (int i = 0; i < cnt4 && idx < n; ++i) {
17                 buf[idx++] = tmp[i];
18             }
19             if (cnt4 < 4) break;
20         }
21         return idx;
22     }
23 };

 

 

Read N Characters Given Read4 II - Call multiple times

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 may be called multiple times.

 1 // Forward declaration of the read4 API.
 2 int read4(char *buf);
 3 
 4 class Solution {
 5 private:
 6     char tmp[4];
 7     int tmp_idx = 0, tmp_len = 0;
 8 public:
 9     /**
10      * @param buf Destination buffer
11      * @param n   Maximum number of characters to read
12      * @return    The number of characters read
13      */
14     int read(char *buf, int n) {
15         int idx = 0;
16         bool flag;
17         while (idx < n) {
18             flag = true;
19             if (tmp_idx == tmp_len) {
20                 tmp_idx = 0;
21                 tmp_len = read4(tmp);
22                 if (tmp_len != 4) flag = false;
23             }
24             for (; tmp_idx < tmp_len && idx < n; ++tmp_idx) {
25                 buf[idx++] = tmp[tmp_idx];
26             }
27             if (!flag) break;
28         }
29         return idx;
30     }
31 };

 

posted @ 2015-09-06 11:33  Eason Liu  阅读(607)  评论(0编辑  收藏  举报