Friday, November 27, 2015

[leetcode]Read N Characters Given Read4

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    public int read(char[] buf, int n) {
        int sum = 0;
        char[] temp = new char[4];
        int readNum = 4;
        while (sum < n && readNum == 4){
            readNum = read4(temp);
            for (int i = 0; i < readNum && sum < n; i++){
                buf[sum++] = temp[i];
            }
        }
        return sum;
    }
}

No comments:

Post a Comment