Leetcode-Read N Characters Given Read4

LiBlog發表於2014-12-13

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 }

 

相關文章