[LeetCode] Read N Characters Given Read4

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 read
10      */
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 };
复制代码

 

posted @   jianchao-li  阅读(267)  评论(0编辑  收藏  举报
编辑推荐:
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
阅读排行:
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
点击右上角即可分享
微信分享提示