题目
我是编码的新手,现在我想得到两个数组的总和......实际上是所有元素的总和。我很感激你的帮助。
P.S.每个数组仅包含整数。输出也是一个数字。
测试用例:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD development by writing your own tests
public class SolutionTest {
@Test
public void sampleTests() {
assertEquals(21, Sum.arrayPlusArray(new int[]{1,2,3}, new int[]{4,5,6}));
assertEquals(-21, Sum.arrayPlusArray(new int[]{-1,-2,-3}, new int[]{-4,-5,-6}));
assertEquals(15, Sum.arrayPlusArray(new int[]{0,0,0}, new int[]{4,5,6}));
assertEquals(2100, Sum.arrayPlusArray(new int[]{100,200,300}, new int[]{400,500,600}));
}
}
解题
My
public class Sum {
public static int arrayPlusArray(int[] arr1, int[] arr2) {
int sum = 0;
for (int i = 0; i<arr1.length; i++) {
sum += arr1[i];
}
for (int i = 0; i<arr2.length; i++) {
sum += arr2[i];
}
return sum;
}
}
Other
import java.util.stream.*;
public class Sum {
public static int arrayPlusArray(int[] arr1, int[] arr2) {
return IntStream.of(arr1).sum() + IntStream.of(arr2).sum();
}
}
public class Sum {
public static int arrayPlusArray(int[] arr1, int[] arr2) {
return sumArrayElements(arr1) + sumArrayElements(arr2);
}
private static int sumArrayElements(int[] arr) {
int sum = 0;
for (int i : arr) {
sum += i;
}
return sum;
}
}
后记
原来我还在想有没有库函数有类似这样的方法呢。
网友评论