题目描述
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
class Solution {
public:
int Sum_Solution(int n)
{
int sum=0;
return add(n,sum);
}
int add(int n, int &sum)
{
n && add(n-1, sum);
return (sum+=n);
}
};
利用虚函数
- #include <iostream>
- using namespace std;
- class A;
- A* Array[2];
- class A
- {
- public:
- virtual int Sum(int n)
- {
- return 0;
- }
- };
- class B:public A
- {
- public:
- virtual int Sum(int n)
- {
- return Array[!!n]->Sum(n-1)+n;
- }
- };
- int solution2_Sum(int n)
- {
- A a;
- B b;
- Array[0]=&a;
- Array[1]=&b;
- int value=Array[1]->Sum(n);
- return value;
- }
- int main()
- {
- cout<<solution2_Sum(100)<<endl;
- return 0;
- }
- 利用函数指针
- #include <iostream>
- using namespace std;
- typedef int (*fun)(int);
- int solution_f1(int i)
- {
- return 0;
- }
- int solution_f2(int i)
- {
- fun f[2]={solution_f1, solution_f2};
- return i+f[!!i](i-1);
- }
- void main()
- {
- cout<<solution_f2(100)<<endl;
- }