Simple C++ solution


  • 0
    P

    The idea is very simple — do maximum number of possible reads OR stop when the number of bytes read from read4 is less than 4.

    // Forward declaration of the read4 API.
    int read4(char *buf);
    
    class Solution {
    public:
        /**
         * @param buf Destination buffer
         * @param n   Maximum number of characters to read
         * @return    The number of characters read
         */
        int read(char *buf, int n) 
        {
            int res = 0;
            for(int i = 0, cur = 4; i <= n/4 && cur == 4; i++){
                cur = read4(buf + res);
                res += cur;
            }
            return min(res, n);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.