158.Read N Characters Given Read4 II — Call multiple times

Link

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.

Example 1:

Given buf = "abc"
read("abc", 1) // returns "a"
read("abc", 2); // returns "bc"
read("abc", 1); // returns ""

Example 2:

Given buf = "abc"
read("abc", 4) // returns "abc"
read("abc", 1); // returns ""

Note: The read function may be called multiple times.

Solution

用static的global變數紀錄上次讀到哪,每次讀取時從那裏開始往下讀就可以,當讀到最後沒值就還傳""

static int index = 0;

 public int reads(char[] buf, int n) {
        char[] internal = new char[4];
        int offset = 0;
        while (true) {
            int count = read4(internal);
            for (int i = 0; i < count && offset < n; i++) {
                buf[offset++] = internal[i];
            }
            if (offset == n || count == 0) {
                break;
            }
        }
        return offset;
    }

Last updated

Was this helpful?