Leetcode 157 Solution

This article provides solution to leetcode question 157 (read-n-characters-given-read4)

https://leetcode.com/problems/read-n-characters-given-read4

Solution

// 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 i = 0;
	   int j = 0;
	   int k = 0;
	   while( k < n ){
	    	char reserved[4];
	    	if( i == j ){
	    	    i = 0;
	    	    j = read4( reserved );

	    	    if( j == 0 )
	    	        return k;
	    	}

	    	buf[k++] = reserved[i++];
        }
        return k;
    }
};