码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-Read N Characters Given Read4

时间:2014-12-13 06:07:23      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   ar   color   sp   for   strong   

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.

Solution:

 1 /* The read4 API is defined in the parent class Reader4.
 2       int read4(char[] buf); */
 3 
 4 public class Solution extends 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         char[] tempBuf = new char[4];
12         int left = n;
13         while (left>0){
14             int num = read4(tempBuf);
15             //if the read number is larger then what we need, then we just put the left number of chars into buf.
16             int end = Math.min(num,left);
17             for (int i=0;i<end;i++){
18                 buf[n-left] = tempBuf[i];
19                 left--;
20             }
21   
22             //If reach EOF.
23             if (left>0 && num<4) break;
24         }
25          
26         return n-left;   
27         
28     }
29 }

 

Leetcode-Read N Characters Given Read4

标签:des   style   blog   io   ar   color   sp   for   strong   

原文地址:http://www.cnblogs.com/lishiblog/p/4160859.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!