Skip to content

Commit 0d7ec13

Browse files
EASY/src/easy/ReadNCharactersGivenRead4.java
1 parent e43ed48 commit 0d7ec13

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package easy;
2+
3+
/**
4+
* 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.
18+
*/
19+
public class ReadNCharactersGivenRead4 {
20+
public int read(char[] buf, int n) {
21+
int index = 0, next= 0;
22+
char[] buffer = new char[4];
23+
while(index < n && (next = read4(buffer)) != 0){
24+
for(int i = 0; i < next && index < n; index++, i++){
25+
buf[index] = buffer[i];
26+
}
27+
}
28+
return index;
29+
}
30+
31+
private int read4(char[] buffer) {
32+
//this is a fake method to make Eclipse happy
33+
return 0;
34+
}
35+
}

0 commit comments

Comments
 (0)