72.求1+2+…+n

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

数据范围:

1≤n≤50000。

样例:

输入:10
输出:55

代码:

class Solution {
    public long getSum(int n) {
        //1+2+...+n的和为n*(n+1)/2
        //res为累加结果
        //a保存n的值,b保存n+1的值
        long res = 0,a = n,b = n+1;
        //快速乘算法:通过位运算计算a*b的值
        while(a!=0){
            //如果a的最低位是1,则将当前的b值加到结果中
            if((a&1)!=0)res+=b;
            //a右移一位(相当于除以2)
            a>>=1;
            //b左移一位(相当于乘以2)
            b<<=1;
        }
        //最终结果需要除以2
        return res>>1;
    }
}
posted @ 2025-06-02 10:22  回忆、少年  阅读(9)  评论(0)    收藏  举报