Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1a1a9fb

Browse files
refactor 157
1 parent 714d364 commit 1a1a9fb

File tree

1 file changed

+35
-25
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+35
-25
lines changed
Lines changed: 35 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,46 @@
11
package com.fishercoder.solutions;
22

33
/**
4+
* 157. Read N Characters Given Read4
5+
*
46
* The API: int read4(char *buf) reads 4 characters at a time from a file.
5-
*
6-
* The return value is the actual number of characters read. For example, it returns 3 if there is
7-
* only 3 characters left in the file.
8-
*
9-
* By using the read4 API, implement the function int read(char *buf, int n) that reads n characters
10-
* from the file.
11-
*
12-
* Note: The read function will only be called once for each test case.
13-
*/
14-
15-
/**
16-
* The problem description is pretty ambiguous, actually the problem means to Keep reading until
17-
* either you have gotten n characters or there is no more characters to read.
7+
*
8+
* 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.
9+
*
10+
* By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
11+
*
12+
* Example 1:
13+
*
14+
* Input: buf = "abc", n = 4
15+
* Output: "abc"
16+
* Explanation: The actual number of characters read is 3, which is "abc".
17+
*
18+
* Example 2:
19+
*
20+
* Input: buf = "abcde", n = 5
21+
* Output: "abcde"
22+
*
23+
* Note:
24+
* The read function will only be called once for each test case.
25+
*
1826
*/
1927
public class _157 {
20-
public int read(char[] buf, int n) {
21-
int index = 0;
22-
int next = 0;
23-
char[] buffer = new char[4];
24-
while (index < n && (next = read4(buffer)) != 0) {
25-
for (int i = 0; i < next && index < n; index++, i++) {
26-
buf[index] = buffer[i];
28+
public static class Solution1 {
29+
public int read(char[] buf, int n) {
30+
int index = 0;
31+
int next = 0;
32+
char[] buffer = new char[4];
33+
while (index < n && (next = read4(buffer)) != 0) {
34+
for (int i = 0; i < next && index < n; index++, i++) {
35+
buf[index] = buffer[i];
36+
}
2737
}
38+
return index;
2839
}
29-
return index;
30-
}
3140

32-
private int read4(char[] buffer) {
33-
//this is a fake method to make Eclipse happy
34-
return 0;
41+
private int read4(char[] buffer) {
42+
//this is a fake method to make Eclipse happy
43+
return 0;
44+
}
3545
}
3646
}

0 commit comments

Comments
 (0)