Finally get question understood and AC by C++


  • 1
    G
    class Solution {
    private:
        char _buffer[4];
    	int _bufferIndex;
    	int _endCount;
    
    public:
        Solution()
        {
            memset(_buffer,0,4);
    		_bufferIndex=0;
    		_endCount=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;
            
    		char* p=buf;
    		// read from buffer first
    		int m=0;
    		while(m<n && _bufferIndex<_endCount)
    		{
    			buf[m++]=_buffer[_bufferIndex++];
    			p++;
    		}
    
    		if(m==n) return n;
    
    		//read from file
    		while(1)
    		{
    			int r=read4(_buffer);
    			int t=m+r;
    			
    			if(t>=n)
    			{
    				memcpy(p,_buffer,n-m);
    				_endCount=r;
    				_bufferIndex=n-m;
    
    				return n;
    			}
    			else
    			{
    				memcpy(p,_buffer,r);
    				p+=r;
    				m=t;
    				if(r<4)
    				{
    					_bufferIndex=0;
    					_endCount=0;
    
    					return m;
    				}
    			}
    		}
        }
    };

Log in to reply
 

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