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

题目描述

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

解题思路

  • 方法一:使用returnand来保证递归到0截止;
  • 方法二:使用tryexceptassert语句来保证递归到0截止;
  • 方法三:直接使用公式,乘法改为幂,除2改为右移1位。

代码

Python(2.7.3)

方法一

1
2
3
4
5
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
return n > 0 and self.Sum_Solution(n - 1) + n

运行时间:28ms
占用内存:5752k

方法二

1
2
3
4
5
6
7
8
9
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
try:
assert n > 0
return n + self.Sum_Solution(n - 1)
except:
return 0

运行时间:30ms
占用内存:5712k

方法三

1
2
3
4
5
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
return (n ** 2 + n) >> 1

运行时间:23ms
占用内存:5832k