[Leetcode] 157. Read N Characters Given Read4 解题报告
来源:互联网 发布:端口镜像是做什么用的 编辑:程序博客网 时间:2024/06/18 03:03
题目:
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.
思路:
题目的思路不是很难,主要是判断各个终止条件:如果还有剩余的字符需要读取(n > 0),那么就调用API函数进行读取。读取之后需要判断返回值,一旦发现返回值为0,说明文件中的内容已经被全部读取,则提前返回。否则就需要判断返回值和剩余需要读取的字符的大小,根据比较的结果向buffer中复制读取的内容,并且更新n的值。
代码:
// 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) { int ret = 0; char temp[4]; while(n > 0) { // still have content to read int num = read4(temp); if(num == 0) { // nothing left to read break; } if(n > num) { // put all the content to buffer for(int i = 0; i < num; ++i) { buf[ret++] = temp[i]; } n -= num; } else { // only partial contents are left to put into the buffer for(int i = 0; i < n; ++i) { buf[ret++] = temp[i]; } n = 0; } } return ret; }};
阅读全文
0 0
- [leetcode] 157. Read N Characters Given Read4 解题报告
- [Leetcode] 157. Read N Characters Given Read4 解题报告
- [LeetCode] 157. Read N Characters Given Read4
- LeetCode 157. Read N Characters Given Read4
- [leetcode] 158. Read N Characters Given Read4 II - Call multiple times 解题报告
- leetcode Read N Characters Given Read4
- leetcode 157: Read N Characters Given Read4
- [LeetCode] Read N Characters Given Read4
- Leetcode: Read N Characters Given Read4
- *LeetCode-Read N Characters Given Read4
- [leetcode 157] Read N Characters Given Read4
- LeetCode 157: Read N Characters Given Read4
- Leetcode 157 Read N Characters Given Read4
- 157. Read N Characters Given Read4
- 157. Read N Characters Given Read4
- Read N Characters Given Read4
- Read N Characters Given Read4
- Read N Characters Given Read4
- struts零散知识累积(一)
- Magento 2中文文档教程
- C#方法重载(overload)、重写(覆盖)(override)、隐藏(new) -第四天
- USACO之Section1.1.3 Friday the Thirteenth
- 数据库迁移之从oracle 到 MySQL
- [Leetcode] 157. Read N Characters Given Read4 解题报告
- openssl 错误处理
- 一些有趣的算法题收集-Category
- UESTC 1639 云中谁寄锦书来?雁字回时,月满西楼。 Dijkstra拓展
- Shell中的字符串处理
- 语音控制AR.Drone的安卓上实现
- 在NanoPi-NEO上直接编译 LIVE555
- Ubuntu 安装 Neo4j 详细步骤
- underscore.js中如何判断两个对象的内容相同