老卫带你学---剑指offer刷题系列(47.求1+2+3+...+n)

47.求1+2+3+…+n

问题:

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

解决:

思想:

1-n之和可以采用高斯公式:
S=(1+n)*n/2

python代码:

# -*- coding:utf-8 -*-
class Solution:
    def Sum_Solution(self, n):
        # write code here
        return (1+n)*n//2
发布了160 篇原创文章 · 获赞 30 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/yixieling4397/article/details/105064693