157. Read N Characters Given Read4

題目:
The API: int read4(char *buf) reads 4 characters at a time from a file.java

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.api

By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.code

Note:
The read function will only be called once for each test case.it

解答:
讀懂題目很重要,仍是要多寫寫這種實際的api的問題。io

/* 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) {
        boolean end = false;
        int total = 0;
        char[] temp = new char[4];
        //有兩種狀況:1. 須要read的character個數是n,但實際文件中character個數小於n個,因此咱們只能返回實際character的個數;2. 須要read的character個數n小於實際文件中的個數,因此最後一步只須要n - total個character就能夠。
        while (!end && total < n) {
            int count = read4(temp);
            //實際文件讀到頭了的狀況
            end = count < 4;
            //須要讀的文件個數達到了的狀況
            count = Math.min(count, n - total);
            for (int i = 0; i < count; i++) {
                buf[total++] = temp[i];
            }
        }
        return total;
    }
}
相關文章
相關標籤/搜索