Solution in C++


  • 1
    F
        int read(char *buf, int n) {
            int readBytes = 0;
        	int totalRead = 0;
    
        	while (n >= 4) {
        		readBytes = read4(buf);
        		buf += readBytes;
        		n -= readBytes;
        		totalRead += readBytes;
    
        		if (readBytes != 4)
        			break;
        	}
    
        	if (n > 0) {
        		char *buf2 = new char[4];
        		readBytes = read4(buf2);
        		int smaller = (n < readBytes ? n : readBytes);
        		totalRead += smaller;
        		memcpy(buf, buf2, smaller);
        	}
    
        	return totalRead;
        }

  • 0
    J

    Why do you need to create "buf2" when n > 0?


Log in to reply
 

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