Sum All Numbers in a Range

Posted 梦如影

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sum All Numbers in a Range相关的知识,希望对你有一定的参考价值。

function sumAll(arr) {
  //return 1;
  var result = 0,
      a = Math.max(arr[0],arr[1]),
      b = Math.min(arr[0],arr[1]);
  while (a >= b){
    result += b;
    b++;
  }
  return result;
}

sumAll([1, 4]);

function sumAll(arr) {
  //return 1;
  return (arr[0] + arr[1]) * (Math.abs(arr[0] - arr[1]) + 1) / 2;
}

sumAll([1, 4]);

  公式法

function sumAll(arr) {
  var arryA=[];
   var max=Math.max.apply(null,arr);
   var min=Math.min.apply(null,arr);
   var sum=0;
   var sumFun=function(max,min){
      for(var i=0;i<(max-min+1);i++){
         arryA.push(min+i);
      }
      console.log(arryA);
      var value=arryA.reduce(function(previousValue,currentValue){
         return previousValue+currentValue;
      });
      return value;
   };
   sum=sumFun(max,min);
   return sum;  
}

sumAll([1, 4]);

  

 

以上是关于Sum All Numbers in a Range的主要内容,如果未能解决你的问题,请参考以下文章

Sum All Numbers in a Range

FreeCodeCamp之sum all numbers in a range

FCC_Intermediate Algorithm Scripting_Sum All Numbers in a Range

leetcode No448. Find All Numbers Disappeared in an Array

Find All Numbers Disappeared in an Array

#Leetcode# 448. Find All Numbers Disappeared in an Array