C++ 0ms solution


  • 0
    X

    The first version of code considered the case of n is larger than the file size

    // 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) {
            char * tmpBuffer=new char[4];
            int theRest=n%4;
            int numEach=0;
            int i=0;
            while( (numEach = read4(tmpBuffer)) && i < n ) {
                if(i + numEach > n) {
                    memcpy(buf+i, tmpBuffer, theRest);
                    return n;
                }
                memcpy(buf+i, tmpBuffer, numEach);
                i += numEach;
            }
            return i;
        }
    };

  • 0
    X
    // 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 haveRead = 0;
            int numbersRead = 0;
            char tmpBuffer[4] = {0};
            char * ptr = buf;
            while ((numbersRead = read4(tmpBuffer)) == 4 && haveRead + 4 <= n) {
                memcpy(ptr, tmpBuffer, 4);
                haveRead += 4;
                ptr += 4;
            }
            int remaningBytes = numbersRead > (n - haveRead) ? (n - haveRead) : numbersRead;
            memcpy(ptr, tmpBuffer, remaningBytes);
            haveRead += remaningBytes;
            return haveRead;
        }
    };

Log in to reply
 

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