1.7 KiB
1.7 KiB
id, title, isRequired, challengeType, forumTopicId, localeTitle
id | title | isRequired | challengeType | forumTopicId | localeTitle |
---|---|---|---|---|---|
a3566b1109230028080c9345 | Sum All Numbers in a Range | true | 5 | 16083 | 范围内的数字求和 |
Description
例如,sumAll([4,1])
应该返回 10
,因为从 1 到 4 (包含 1、4)的所有数字的和是 10
。
如果你遇到了问题,请点击帮助。
Instructions
Tests
tests:
- text: <code>sumAll([1, 4])</code>应该返回一个数字。
testString: assert(typeof sumAll([1, 4]) === 'number');
- text: <code>sumAll([1, 4])</code>应该返回 10。
testString: assert.deepEqual(sumAll([1, 4]), 10);
- text: <code>sumAll([4, 1])</code>应该返回 10。
testString: assert.deepEqual(sumAll([4, 1]), 10);
- text: <code>sumAll([5, 10])</code>应该返回 45。
testString: assert.deepEqual(sumAll([5, 10]), 45);
- text: <code>sumAll([10, 5])</code>应该返回 45。
testString: assert.deepEqual(sumAll([10, 5]), 45);
Challenge Seed
function sumAll(arr) {
return 1;
}
sumAll([1, 4]);
Solution
function sumAll(arr) {
var sum = 0;
arr.sort(function(a,b) {return a-b;});
for (var i = arr[0]; i <= arr[1]; i++) {
sum += i;
}
return sum;
}