Simple C++ 0ms solution, rather straightforward


  • 0
    X

    Apparently the read() function shouldn't be stateless, so we always maintain an intermediate buffer of size 4 to track the remainder of what has already been read from the file. Below is a C++ incarnation of this.

    class Solution {
    public:
        char prevBuf[4];
        int prevBufNextToReturn;
        int prevBufActual;
        
        Solution() : prevBufNextToReturn(0), prevBufActual(0)
        {
        }
    
        /**
         * @param buf Destination buffer
         * @param n   Maximum number of characters to read
         * @return    The number of characters read
         */
        int read(char *buf, int n) {
            if(n <= 0)
            {
                return 0;
            }
            
            int actual = 0;
            while(actual < n && prevBufNextToReturn < prevBufActual)
            {
                buf[actual++] = prevBuf[prevBufNextToReturn++];
            }
            if(prevBufNextToReturn == prevBufActual)
            {
                prevBufActual = 0;
                prevBufNextToReturn = 0;
            }
            if(actual == n)
            {
                return actual;
            }
            
            for(;;)
            {
                prevBufActual = read4(&prevBuf[0]);
                if(!prevBufActual) return actual;
                while(actual < n && prevBufNextToReturn < prevBufActual)
                {
                    buf[actual++] = prevBuf[prevBufNextToReturn++];
                }
                if(prevBufNextToReturn == prevBufActual)
                {
                    prevBufNextToReturn = 0;
                    prevBufActual = 0;
                }
                if(actual == n)
                {
                    return actual;
                }
            }
            return actual; // shouldn't really get here
        }
    };

Log in to reply
 

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