要求
题目
We'll pass you an array of two numbers. Return the sum of those two numbers and all numbers between them.
The lowest number will not always come first.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
given code
function sumAll(arr) {
return 1;
}
sumAll([1, 4]);
分析
分别获取最大值和最小值,然后依次相加
- 获取最大值
- 获取最小值
- 从小到大依次相加
function sumAll(arr) {
var max = Math.max(arr[0],arr[1]);
var min = Math.min(arr[0],arr[1]);
return (max+min)*(max-min+1)/2;
}
sumAll([1, 4]);