157. Read N Characters Given Read4 - cocoder39/coco39_LC GitHub Wiki

157. Read N Characters Given Read4

Notes 2021:

conditions to terminate reading:

    1. entire file has been read: read_from_read4 < 4
    1. has read n chars: has_read == n
class Solution:
    def read(self, buf, n):
        """
        :type buf: Destination buffer (List[str])
        :type n: Number of characters to read (int)
        :rtype: The number of actual characters read (int)
        """
        buf4 = [' '] * 4
        has_read, read_from_read4 = 0, 4
        while has_read < n and read_from_read4 == 4:
            read_from_read4 = read4(buf4)
            for i in range(read_from_read4):
                buf[has_read] = buf4[i] 
                has_read += 1
                if has_read == n:
                    return has_read
        
        return has_read

======================================================================

  • res < n => n > file length => return res
  • res >= n => n <= file length => return n
int read(char *buf, int n) {
        int res = 0;
        while (res < n) {
            int cur = read4(buf);
            res += cur;
            if (cur < 4)    break;
            buf += cur;
        }
        //break conditions: res >= n (return n) or cur < 4 (return res)
        return min(res, n);
    }
⚠️ **GitHub.com Fallback** ⚠️