|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | /**
|
| 4 | + * 157. Read N Characters Given Read4 |
| 5 | + * |
4 | 6 | * 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 | + * |
18 | 26 | */
|
19 | 27 | 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 | + } |
27 | 37 | }
|
| 38 | + return index; |
28 | 39 | }
|
29 |
| - return index; |
30 |
| - } |
31 | 40 |
|
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 | + } |
35 | 45 | }
|
36 | 46 | }
|
0 commit comments