博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Read N Characters Given Read4
阅读量:5046 次
发布时间:2019-06-12

本文共 1453 字,大约阅读时间需要 4 分钟。

To read n characters, we first call read4 for n / 4 times. For example, if we want to read 10 characters, we will read them in the 8 (4 * 2) + 2 manner by first calling read4 for 2 (n / 4) times to read the 8 characters.

Then we see if there is any remaining number of characters to read (in this case, remain = 2).

If remain > 0, we read them again using read4. However, we may not be able to read all of them. For example, buf has 9 characters and we need to read 10. After reading the characters we can only read the remaining 1 character. In this case, we simply add the minimum of remain and the actual number of characters read by read4 to the couter (total) and return it.

Otherwise, we are done and just return n.

The code is as follows.

1 // Forward declaration of the read4 API. 2 int read4(char *buf); 3  4 class Solution { 5 public: 6     /** 7      * @param buf Destination buffer 8      * @param n   Maximum number of characters to read 9      * @return    The number of characters read10      */11     int read(char *buf, int n) {12         int total = 0;13         for (int i = 0; i < n / 4; i++) {14             int read = read4(buf + total);15             total += read;16         }17         int remain = n - total;18         if (remain) {19             int read = read4(buf + total);20             return total + min(read, remain);21         }22         return n;23     }24 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4554948.html

你可能感兴趣的文章
PHP结合MYSQL记录结果分页呈现(比较实用)
查看>>
Mysql支持的数据类型
查看>>
openSuse beginner
查看>>
Codeforces 620E(线段树+dfs序+状态压缩)
查看>>
Windows7中双击py文件运行程序
查看>>
Market entry case
查看>>
bzoj1230 开关灯 线段树
查看>>
LinearLayout
查看>>
学习python:day1
查看>>
css3动画属性
查看>>
第九次团队作业-测试报告与用户使用手册
查看>>
Equal Sides Of An Array
查看>>
CentOS笔记-用户和用户组管理
查看>>
Mongodb 基本命令
查看>>
Qt中QTableView中加入Check列实现
查看>>
“富豪相亲大会”究竟迷失了什么?
查看>>
控制文件的备份与恢复
查看>>
返回代码hdu 2054 A==B?
查看>>
Flink独立集群1
查看>>
iOS 8 地图
查看>>