題目描述
求1+2+3+...+n氓涣,要求不能使用乘除法牛哺、for、while劳吠、if引润、else、switch痒玩、case等關(guān)鍵字及條件判斷語句(A?B:C)淳附。
示例
輸入
5
輸出
15
思路
這一題根據(jù)要求不能使用乘除法、for蠢古、while奴曙、if、else草讶、switch洽糟、case等關(guān)鍵字及條件判斷語句(A?B:C)。所以我們?yōu)榱嗽谶f歸中做到及時跳出堕战,我們使用了&&的短路原則坤溃,即當&&的前半部分發(fā)生錯誤時,后半部分的判斷條件不會被調(diào)用嘱丢,即打破遞歸(當n == 0時薪介,&&條件判斷為false)。
代碼
#include "iostream"
#include "string"
#include "vector"
using namespace std;
int Sum_Solution(int n) {
int ans = n;
n && (ans += Sum_Solution(n-1));
return ans;
}