題目描述
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等關(guān)鍵字及條件判斷語(yǔ)句(A?B:C)。
示例
輸入
5
輸出
15
思路
這一題根據(jù)要求不能使用乘除法、for、while、if、else、switch、case等關(guān)鍵字及條件判斷語(yǔ)句(A?B:C)。所以我們?yōu)榱嗽谶f歸中做到及時(shí)跳出,我們使用了&&的短路原則,即當(dāng)&&的前半部分發(fā)生錯(cuò)誤時(shí),后半部分的判斷條件不會(huì)被調(diào)用,即打破遞歸(當(dāng)n == 0時(shí),&&條件判斷為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;
}