recursive C++ solution


  • 0
    G
    class Solution {
    public:
        /**
         * @param buf Destination buffer
         * @param n   Maximum number of characters to read
         * @return    The number of characters read
         */
        
        vector<char> cache;
        int beginIdx;
        int endIdx;
        
        Solution():
        cache(4,'0'),
        beginIdx(cache.size()),
        endIdx(cache.size()){}
        
        int read(char *buf, int n) {
            if(n == 0){
                return 0;
            }
            
            if(beginIdx < endIdx){
                memcpy(buf,&cache[beginIdx],min(endIdx - beginIdx,n));
                int temp = min(endIdx - beginIdx,n);
                beginIdx += temp; 
                return temp + read(buf + temp,n - temp);
            }
        
            int res = read4(&cache[0]);
            beginIdx = 0;
            endIdx = res;
        
            if(res == 0){
                return res;
            }
            
            return read(buf,n);
        }
    };
    

Log in to reply
 

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