求和两个整数之间的所有数字 [英] Sum all numbers between two integers

查看:259
本文介绍了求和两个整数之间的所有数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标

给定数组中的两个数字,将所有数字相加,包括(和之间)两个整数(例如[4,2] ] - > 2 + 3 + 4 = 9 )。

Given two numbers in an array, sum all the numbers including (and between) both integers (e.g [4,2] -> 2 + 3 + 4 = 9).

我设法解决了这个问题,但想知道是否还有更多优雅的解决方案(特别是使用Math.max和Math.min) - 请参阅下面的更多问题...

I've managed to solve the question but was wondering if there is a more elegant solution (especially using Math.max and Math.min) - see below for more questions...

我的解决方案

//arrange array for lowest to highest number
function order(min,max) {
  return min - max;
}


function sumAll(arr) {
  var list = arr.sort(order);
  var a = list[0]; //smallest number
  var b = list[1]; //largest number
  var c = 0;

  while (a <= b) {
    c = c + a; //add c to itself
    a += 1; // increment a by one each time
  }

  return c;
}

sumAll([10, 5]);

我的问题


  1. 有更有效的方法吗?

  2. 我如何将Math.max()和Math.min()用于数组?


推荐答案

var array = [4, 2];
var max = Math.max.apply(Math, array); // 4
var min = Math.min.apply(Math, array); // 2

function sumSeries (smallest, largest) {
    // The formulate to sum a series of integers is
    // n * (max + min) / 2, where n is the length of the series.
    var n = (largest - smallest + 1);
    var sum = n * (smallest + largest) / 2; // note integer division

    return sum;
}

var sum = sumSeries(min, max);
console.log(sum);

这篇关于求和两个整数之间的所有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆