时间限制:1秒
空间限制:32768K
热度指数:68900
题目描述
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
链接:https://www.nowcoder.com/practice/7a0da8fc483247ff8800059e12d7caf1?tpId=13&tqId=11200&tPage=3&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
这是道简单而又有趣的题目,因为简单求1加到n,应该都会,但题目限定了如此多的条件,一看就是为了让做题人用递归吧,关键是递归结束条件,因为不能用if else,就没有了判断,只能用其他来做结束条件,逻辑与恰到好处的符合这个条件,每次递归n递减,直到为0时,逻辑与,就像发生了短路,结束程序。
代码:
class Solution {
public:
int Sum_Solution(int n) {
int res=n;
res&&(res+=Sum_Solution(n-1));
return ans;
}
};
public:
int Sum_Solution(int n) {
int res=n;
res&&(res+=Sum_Solution(n-1));
return ans;
}
};