每天一道算法题(1) ——不用乘除法求和1+2+…+n

题目:求1+2+…+n,要求不能使用乘除法、forwhileifelseswitchcase等关键字以及条件判断语句(A?B:C)。


方法1:使用函数指针。

typedef int (*function)(int);
int func1(int n){
	return 0;
}
int func2(int n){
	function f[2]={func1,func2};
	return n+f[!!n](n-1);
}
void main(){
	cout<<func2(10);
}



  方法2:使用构造函数。

class test{
	static int N;
	static int sum;
public :
	test(){sum+=++N;}
	static void reset(){N=sum=0;}
	static int getSum(){return sum;}
};
int test::N = 0;
int test::sum = 0;

void main(){
	test::reset();
	test *p=new test[10];
	cout<<test::getSum();
	delete []p;
}



方法3:使用虚函数的编译多态性

class A{
  public:
	virtual int sum(int n){return 0;};
};
class B:public A
{
    public:
	int sum(int n){
	   A a;B b;
	   A *p[2]={&a,&b};
	   return n+p[!!(n-1)]->sum(n-1);}
};

void main(){
	B b;
	cout<<b.sum(10); 
}



原文地址:https://www.cnblogs.com/engineerLF/p/5393051.html