首页 > 其他 > 详细

Leetcode 157: Read N Characters Given Read4

时间:2017-12-18 11:29:58      阅读:216      评论:0      收藏:0      [点我收藏+]

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 /* The Read4 API is defined in the parent class Reader4.
 2       int Read4(char[] buf); */
 3 
 4 public class Solution : Reader4 {
 5     /**
 6      * @param buf Destination buffer
 7      * @param n   Maximum number of characters to read
 8      * @return    The number of characters read
 9      */
10     public int Read(char[] buf, int n) {
11         int i = 0;
12         bool eof = false;
13         
14         while (i < n && !eof)
15         {
16             var temp = new char[4];
17             int r = Read4(temp);
18             
19             if (r < 4)
20             {
21                 eof = true;
22             }
23             
24             for (int k = 0; k < r; k++)
25             {
26                 buf[i++] = temp[k];
27                 
28                 if (i >= n) break;
29             }
30         }
31         
32         return i;
33     }
34 }

 

Leetcode 157: Read N Characters Given Read4

原文:http://www.cnblogs.com/liangmou/p/8055947.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!