面试题64:1-2+3+...+n

作者: 不会编程的程序猿甲 | 来源:发表于2020-04-19 22:58 被阅读0次

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

    思路:
    利用与运算符的短路效应来完成递归操作
    a and b的结果在a为假时直接返回a,否则返回b,示例如下:

    print("a为真时,1 and 2的结果:", 1 and 2)
    print("a为假时,0 and 2的结果为:",0 and 2)
    
    print("a为真时,1 or 2的结果:", 1 or 2)
    print("a为假时,0 or 2的结果:", 0 or 2)
    

    代码实现:

    class Solution:
        def Sum_Solution(self, n):
            # write code here
            return n and n + self.Sum_Solution(n-1)
    

    提交结果:

    相关文章

      网友评论

        本文标题:面试题64:1-2+3+...+n

        本文链接:https://www.haomeiwen.com/subject/eqbwbhtx.html