每日一道算法题——两个不数字的系列之和相加

每日一道算法题——两个不数字的系列之和相加

javascript 实现
跟数列求和差不多

Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return a or b.

Note: a and b are not ordered!

求两个数的系列相加值

Examples

GetSum(1, 0) == 1   // 1 + 0 = 1
GetSum(1, 2) == 3   // 1 + 2 = 3
GetSum(0, 1) == 1   // 0 + 1 = 1
GetSum(1, 1) == 1   // 1 Since both are same
GetSum(-1, 0) == -1 // -1 + 0 = -1
GetSum(-1, 2) == 2  // -1 + 0 + 1 + 2 = 2
function getSum(a, b) {
    //我的思路
    //1.range(a,b)
    //2.各项相加之和 sum = a+...+b
    //3.return sum
}

JavaScript中没有range函数,要自己实现

const getSum = (a, b)=>{
    let min = Math.min(a, b)
    let max = Math.max(a, b)
    return (max-min+1)*(min + max) / 2
}

有规律的排列,用的是排列公式

function getSum(a, b) {
    if (a=b) return a
    else if (a < b) return a + getSum(a+1, b)
    else return a + getSum(a-1, b)
}
function getSum(a, b) {
    return (Math.abs(a-b)+1) * (a+b) / 2
}
function getSum(a, b) {
    let tmp = 0;
    if(a < b) {
        while(a <=b ) tmp += a++
    } else {
        while(a>=b) tmp += a--
    }
    return tmp
}

js实现sum函数

function sum() {
    var x = 0;
    for (var i = 0; i < arguments.length; ++i) {
        x += arguments[i];
    }
    return x;
}

猜你喜欢

转载自blog.csdn.net/example440982/article/details/80056207