首页 > 代码库 > Leetcode-Read N Characters Given Read4
Leetcode-Read N Characters Given Read4
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 is only 3 characters left in the file.
By using the read4
API, implement the function int read(char *buf, int n)
that reads n characters from the file.
Note:
The read
function will only be called once for each test case.
Solution:
1 /* The read4 API is defined in the parent class Reader4. 2 int read4(char[] buf); */ 3 4 public class Solution extends Reader4 { 5 /** 6 * @param buf Destination buffer 7 * @param n Maximum number of characters to read 8 * @return The number of characters read 9 */10 public int read(char[] buf, int n) {11 char[] tempBuf = new char[4];12 int left = n;13 while (left>0){14 int num = read4(tempBuf);15 //if the read number is larger then what we need, then we just put the left number of chars into buf.16 int end = Math.min(num,left);17 for (int i=0;i<end;i++){18 buf[n-left] = tempBuf[i];19 left--;20 }21 22 //If reach EOF.23 if (left>0 && num<4) break;24 }25 26 return n-left; 27 28 }29 }
Leetcode-Read N Characters Given Read4
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。