本文主要是介绍发散思维能力 求1+2+3+...+n,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
发散思维的特点是思维活动的多向性和交通性,也就是我们在思考问题时注重运用多思路、多方案、多途径地解决问题。对于同一个问题,我们可以从不同的方向、侧面和层次,采用探索、转换、迁移、组合和分解等方法,提出多种创新的解法。
问题:求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)通常有三种解法:公式n(n+1)/2,递归和循环
// ====================方法一:利用构造函数求解====================
class Temp
{
public:Temp() { ++ N; Sum += N; }static void Reset() { N = 0; Sum = 0; }static unsigned int GetSum() { return Sum; }private:static unsigned int N;static unsigned int Sum;
};unsigned int Temp::N = 0;
unsigned int Temp::Sum = 0;unsigned int Sum_Solution1(unsigned int n)
{Temp::Reset();Temp *a = new Temp[n];delete []a;a = NULL;return Temp::GetSum();
}// ====================方法二:利用虚函数求解====================
class A;
A* Array[2];class A
{
public:virtual unsigned int Sum (unsigned int n) { return 0; }
};class B: public A
{
public:virtual unsigned int Sum (unsigned int n) { return Array[!!n]->Sum(n-1) + n; }
};int Sum_Solution2(int n)
{A a;B b;Array[0] = &a;Array[1] = &b;int value = Array[1]->Sum(n);return value;
}// ====================方法三:利用函数指针求解====================
typedef unsigned int (*fun)(unsigned int);unsigned int Solution3_Teminator(unsigned int n)
{return 0;
}unsigned int Sum_Solution3(unsigned int n)
{static fun f[2] = {Solution3_Teminator, Sum_Solution3}; return n + f[!!n](n - 1);
}// ====================方法四:利用模板类型求解====================
template <unsigned int n> struct Sum_Solution4
{enum Value { N = Sum_Solution4<n - 1>::N + n};
};template <> struct Sum_Solution4<1>
{enum Value { N = 1};
};template <> struct Sum_Solution4<0>
{enum Value { N = 0};
};// ====================测试代码====================
void Test(int n, int expected)
{printf("Test for %d begins:\n", n);if(Sum_Solution1(n) == expected)printf("Solution1 passed.\n");elseprintf("Solution1 failed.\n");if(Sum_Solution2(n) == expected)printf("Solution2 passed.\n");elseprintf("Solution2 failed.\n");if(Sum_Solution3(n) == expected)printf("Solution3 passed.\n");elseprintf("Solution3 failed.\n");
}void Test1()
{const unsigned int number = 1;int expected = 1;Test(number, expected);if(Sum_Solution4<number>::N == expected)printf("Solution4 passed.\n");elseprintf("Solution4 failed.\n");
}void Test2()
{const unsigned int number = 5;int expected = 15;Test(number, expected);if(Sum_Solution4<number>::N == expected)printf("Solution4 passed.\n");elseprintf("Solution4 failed.\n");
}void Test3()
{const unsigned int number = 10;int expected = 55;Test(number, expected);if(Sum_Solution4<number>::N == expected)printf("Solution4 passed.\n");elseprintf("Solution4 failed.\n");
}void Test4()
{const unsigned int number = 0;int expected = 0;Test(number, expected);if(Sum_Solution4<number>::N == expected)printf("Solution4 passed.\n");elseprintf("Solution4 failed.\n");
}int _tmain(int argc, _TCHAR* argv[])
{Test1();Test2();Test3();Test4();return 0;
}
这篇关于发散思维能力 求1+2+3+...+n的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!