剑指offer 上用的虚函数挺巧妙的:
class A;
A* shuzu[2];
class A
{
public:
virtual int sum(int n){
return 0;
}
};
class B: public A
{
public:
virtual int sum(int n){
return shuzu[!!n]->sum(n - 1) + n;
}
};
class Solution {
public:
int Sum_Solution(int n)
{
A a ;
B b;
shuzu[0] = &a;
shuzu[1] = &b;
return b.sum(n);
}
};
还有利用&&短路的来实现递归:
链接:https://www.nowcoder.com/questionTerminal/7a0da8fc483247ff8800059e12d7caf1
来源:牛客网
int Sum_Solution(int n) {
int ans = n;
ans && (ans += Sum_Solution(n - 1));
return ans;
}