Leetcode Read N characters Given Read4

Source: Internet
Author: User

The API: int read4(char *buf) reads 4 characters at a time from a file.

The return value is the actual number of characters read. For example, it returns 3 if there are only 3 characters left in the file.

read4by using the API, implement the function that int read(char *buf, int n) reads n characters from the file.

Note:
The function is only being read called once for each test case.

Problem Solving Ideas:

start to understand the test instructions error, read 4 characters each time, not read from the BUF, but read from the file, deposited into BUF. If Read4 < 4, the end of the file is read. At the same time think of File.length > N, each time you want to determine the correct length to read into the BUF, that is max.min (count, N-total)

Java Code:

/*The read4 API is defined in the parent class Reader4. int Read4 (char[] buf); */ Public classSolutionextendsReader4 {/**     * @parambuf Destination Buffer *@paramn Maximum number of characters to read *@returnThe number of characters read*/     Public intReadChar[] buf,intN) {BooleanEOF =false;//End of File        Char[] temp =New Char[4]; intTotal = 0;  while(!eof && Total <N) {            intCount =read4 (temp); if(Count < 4) {EOF=true; }            //get the actual countCount = Math.min (count, N-Total );  for(inti = 0; i< count; i++) {Buf[total++] =Temp[i]; }        }        returnTotal ; }}

Reference:

1. Https://leetcode.com/discuss/44743/another-accepted-java-solution

2. http://bangbingsyb.blogspot.com/2014/11/leetcode-read-n-characters-given-read4.html

Leetcode Read N characters Given Read4

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.