[LeetCode] Read N Characters Given Read4 I & II
2015-09-06 11:33
232 查看
Read N Characters Given Read4
The API:
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
Note:
The
Read N Characters Given Read4 II - Call multiple times
The API:
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
Note:
The
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
read4API, implement the function
int read(char *buf, int n)that reads n characters from the file.
Note:
The
readfunction will only be called once for each test case.
// 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) { char tmp[4]; int idx = 0, cnt4; while (idx < n) { cnt4 = read4(tmp); for (int i = 0; i < cnt4 && idx < n; ++i) { buf[idx++] = tmp[i]; } if (cnt4 < 4) break; } return idx; } };
Read N Characters Given Read4 II - Call multiple times
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
read4API, implement the function
int read(char *buf, int n)that reads n characters from the file.
Note:
The
readfunction may be called multiple times.
// Forward declaration of the read4 API. int read4(char *buf); class Solution { private: char tmp[4]; int tmp_idx = 0, tmp_len = 0; 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 idx = 0; bool flag; while (idx < n) { flag = true; if (tmp_idx == tmp_len) { tmp_idx = 0; tmp_len = read4(tmp); if (tmp_len != 4) flag = false; } for (; tmp_idx < tmp_len && idx < n; ++tmp_idx) { buf[idx++] = tmp[tmp_idx]; } if (!flag) break; } return idx; } };
相关文章推荐
- 我是菜鸟:网络知识回顾
- Android中Application类用法
- android:configChanges对Activity生命周期的影响
- led area light is better.
- paramiko interactive shell
- php数组操作函数
- C++_运算符重载的注意事项
- Android官-按百分比来设置控件的宽高
- Maven中Pom.xml中主要标签说明
- iOS使用Charles(青花瓷)抓包并篡改返回数据图文详解
- android 布局之滑动探究 scrollTo 和 scrollBy 方法使用说明
- 第一次作业
- Akka第一个案例动手实战开发消息实体类
- iOS 高斯模糊效果
- [性能]StringBuilder与StringBuffer的区别(转)
- 让cocos2d-x 3.0读取cocostudio中的csb文件
- UIKit;多任务
- hql语句---fetch关键字学习
- 利用ServletContext对象实现多个Servlet之间的数据共享
- Swift 创建UIButton