剑指offer 求1+2+3+...+n
问题描述
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
C++代码实现
思路:使用bool
接收防止出错
转载https://blog.nowcoder.net/n/b2ee1ebf470c4f90a1190e5f4a92bbc4?f=comment
int Sum_Solution(int n) {
bool flag = n > 1 && (n += Sum_Solution(n-1));
return n;
}
python2代码实现
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
return n and (n + self.Sum_Solution(n-1))