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 may be called multiple times.

Analysis:

Since the function can be called multiple times, we need to record the left over content in the buffer of read4, and put them in some place. For the next call, we need to read content from the carry over buffer first.

Solution:

 /* The read4 API is defined in the parent class Reader4.
int read4(char[] buf); */ public class Solution extends Reader4 {
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/ public char[] carry;
public int index; public int read(char[] buf, int n) {
int left = n; //Put carry over into buf, and destroy the carry over array!
if (carry!=null){
while (left>0 && index<carry.length){
buf[n-left]=carry[index];
left--;
index++;
}
if (index>=carry.length){
carry=null;
index=-1;
}
} char[] tempBuf = new char[4];
while (left>0){
int num = read4(tempBuf);
//if the read number is larger then what we need, then we just put the left number of chars into buf.
//And put the rest chars into carry array.
if (num>left){
carry = new char[num-left];
for (int i=left;i<num;i++)
carry[i-left] = tempBuf[i];
index = 0;
} int end = Math.min(num,left);
for (int i=0;i<end;i++){
buf[n-left] = tempBuf[i];
left--;
} //If reach EOF.
if (left>0 && num<4) break;
} return n-left; }
}

最新文章

  1. SqlServer 注入技巧
  2. OpenCV学习笔记——点击显示鼠标坐标
  3. 获取真实ip的报告
  4. MSP430F149学习之路——UART
  5. HelloWorld IL代码
  6. XSS 前端防火墙(2):可疑模块拦截
  7. u盘启动盘制作工具
  8. Linux学习之rcp命令
  9. Hadoop 相关问题
  10. CSS空白符处理!
  11. centos6.7系统安装流程
  12. form 表单提交返回值问题
  13. Latex 经常见到的问题和解决方法
  14. drf框架之 路飞学城(第二天)
  15. Nginx详解二十九:基于Nginx的中间件架构设计
  16. OC的反射机制
  17. Fedora 19安装mysql
  18. 定时任务redis锁+自定义lambda优化提取冗余代码
  19. 安装Nginx并为node.js设置反向代理
  20. Python中第三方库的安装

热门文章

  1. 转 【O2O案例】汽车后市场垂直化电子商务:平业模式解析
  2. Javascript addEventListener dispatchEvent
  3. struts2-获取WEB资源
  4. SQL server自定义函数实例
  5. 英特尔&#174; 实感™ SDK 架构
  6. 64位Windows7升级IE11后无法启动的解决办法
  7. php 提交保存成功页面 倒计时 跳转
  8. 如何用C#代码查找某个路径下是否包含某个文件
  9. jquery 中如何将数组转化为json字符串,然后再转化回来?
  10. AMQ学习笔记 - 11. Spring-JmsTemplate之执行