題目:
求1+2+3+...+n,要求不能使用乘除法迁霎、for吱抚、while百宇、if考廉、else、switch携御、case等關(guān)鍵字及條件判斷語句(A?B:C)昌粤。
思路:
利用與運(yùn)算符的短路效應(yīng)來完成遞歸操作
a and b的結(jié)果在a為假時(shí)直接返回a,否則返回b啄刹,示例如下:
print("a為真時(shí)涮坐,1 and 2的結(jié)果:", 1 and 2)
print("a為假時(shí),0 and 2的結(jié)果為:",0 and 2)
print("a為真時(shí)誓军,1 or 2的結(jié)果:", 1 or 2)
print("a為假時(shí)袱讹,0 or 2的結(jié)果:", 0 or 2)
代碼實(shí)現(xiàn):
class Solution:
def Sum_Solution(self, n):
# write code here
return n and n + self.Sum_Solution(n-1)
提交結(jié)果: