[剑指Offer]求1+2+3+...+n

题目描述

求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

还记得当年的高斯么,高斯求和公式:

1+2+3+...+n=(1+n)*n/2

ok,接下来就是很简单的事情了。

public class Solution {
    public int Sum_Solution(int n) {
        int result = (int) (Math.pow(n, 2) + n);
        return result>>1;
    }
}

你可能感兴趣的:(剑指offer)