剑指offer:Python 求1+2+3+...+n 两行代码解决

题目描述

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

思路及Python实现

按照题意,不能使用循环,那循环我们就用递归来代替;不允许使用if条件语句,因此可以借助与运算与短路求值原理,来限制递归结束条件

class Solution:
    def Sum_Solution(self, n):
    	# 通过A and B 运算的短路原理(即A为假时就不会运算B了)来替代if运算
        temp = n > 0 and self.Sum_Solution(n - 1) # 如果n不大于0,就不会继续递归了
        return n + temp


obj = Solution()
print(obj.Sum_Solution(100))

关于递归可以看下拙作:递归的详解

发布了146 篇原创文章 · 获赞 37 · 访问量 7872

猜你喜欢

转载自blog.csdn.net/storyfull/article/details/103535807
今日推荐