- 空间限制:32768K
- 算法知识视频讲解
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
C++实现:
class Solution {
public:
int Sum_Solution(int n) {
int sum = 0;
(n != 0) && (sum = Sum_Solution( n - 1));
return sum + n;
}
};
Python实现:
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
res = n
return n and n + self.Sum_Solution(n-1)
Python中and函数:
x and y:如果x为真,则返回y;如果x为假,则返回x。
x or y:如果x为真,则返回x;如果x为假,则返回y。