美文网首页
Sum All Numbers in a Range

Sum All Numbers in a Range

作者: dma_master | 来源:发表于2016-08-09 23:06 被阅读26次

要求

题目

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]);   

相关文章

网友评论

      本文标题:Sum All Numbers in a Range

      本文链接:https://www.haomeiwen.com/subject/ijbdsttx.html