【发布时间】:2020-11-01 18:33:04
【问题描述】:
这是我的问题,我很难解决这个问题 任务:我们将向您传递一个由两个数字组成的数组。 返回这两个数字的总和加上 它们之间所有数字的总和。最低的数字并不总是排在第一位。
For example, sumAll([4,1]) should return 10 because
sum of all the numbers between 1 and 4 (both inclusive) is 10.
function sumAll(arr) {
Math.min(arr); //finds the lowest number and takes it 1
Math.max(arr); //finds the largest number 4
//must start at the 1st number and loops over until the max value is reached
//0 start at the 0th index of the array
//++ increament by one so 1 2 3 4
//multiply's each number
//.lenght until the lenght of the array is reached
var i;
for (i = 0; i < arr.length; i++) {
i * i;
}
return 1;
}
sumAll([1, 4]);
【问题讨论】:
-
数组中是否总是有 2 个数字?
-
在 O(1) 可以做到的情况下,每个人都在使用循环...
function sum(arr) { const start = arr[0], end = arr[1]; return (end - start + 1) * (start + end) / 2; } -
@D.Pardal 添加一个答案,但一定要先排序
-
@segFault 我正要这样做,但问题被关闭了......
标签: javascript loops max min