题目
你带儿子去森林看猴子。你知道猴子的具体数量(n),但是你的儿子太小,不能看到猴子的总数,他必须从1开始计算它们。
作为一个好父母,你会坐下来和他一起数。给定数字(n),填充一个数组,其中包含所有数字,包括该数字,但不包括零。
例如,如果n = 10:
返回[1,2,3,4,5,6,7,8,9,10]
测试用例:
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runners.JUnit4;
public class MonkeyCounterTest {
@Test
public void basicTests() {
assertArrayEquals(new int[]{1,2,3,4,5},MonkeyCounter.monkeyCount(5));
assertArrayEquals(new int[]{1,2,3},MonkeyCounter.monkeyCount(3));
assertArrayEquals(new int[]{1,2,3,4,5,6,7,8,9},MonkeyCounter.monkeyCount(9));
assertArrayEquals(new int[]{1,2,3,4,5,6,7,8,9,10},MonkeyCounter.monkeyCount(10));
assertArrayEquals(new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20},MonkeyCounter.monkeyCount(20));
}
}
解题
My
public class MonkeyCounter
{
public static int[] monkeyCount(final int n){
int[] arrs = new int[n];
for (int i = 0; i < n; i++) {
arrs[i] = i+1;
}
return arrs;
}
}
Other
import java.util.stream.*;
public class MonkeyCounter
{
public static int[] monkeyCount(final int n) {
return IntStream.rangeClosed(1, n).toArray();
}
}
后记
最近的8kyu级别都挺简单。
网友评论