求1+2+3+...+n(&& 代替if)
求1+2+3+...+n
http://www.nowcoder.com/questionTerminal/7a0da8fc483247ff8800059e12d7caf1
题目不能用乘除法还有判别运算符,循环等
用递归来代替循环。
class Solution {
public:
int Sum_Solution(int n) {
if(n==0)return n;
return n + Sum_Solution(n-1);
}
};
class Solution {
public:
int Sum_Solution(int n) {
int ans = n;
ans && ans += Sum_Solution(n-1); // 代替if语句 当ans = n = 0时,ans+=Sum_..不执行 直接回n
return ans;
}
};