实现1+2+3+...+n。要求不能使用乘除法,for,while,if,else,switch,case,等关键字及条件判断语句。
2017-07-14 11:57
946 查看
问题:求1+2+3+…+n,要求不能使用乘除法,for,while,if,else,switch,case,等关键字及条件判断语句。
解决思路:一般思路就是循环,递归,或者公式n(1+n)/2
方法一:利用构造函数求解
思路:可以让构造函数重复执行++操作
class Temp { public: Temp() { N++; Sum += N; } static void Reset() { N = 0; Sum = 0; } static unsigned int GetSum() { return Sum; } 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 ; delete []a; a = NULL; return Temp::GetSum(); }
方法二:利用虚函数求解,递归
思路:利用虚函数的特性:动态绑定,实现递归,实现二选一的话,可以用布尔变量,!!n 可以将非0转为true,0转为false。
//方法二,利用虚函数的动态绑定,递归 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 sum = Array[1]->Sum(n); return sum; }
方法三:利用函数指针求解,递归
和虚函数类似的思路
// 方法三:利用函数指针求解,递归 typedef unsigned int(*fun)(unsigned int n); unsigned int Solution3_Tem(unsigned int n) { return 0; } unsigned int Sum_Solution3(unsigned int n) { static fun f[2] = { Solution3_Tem, 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 }; }; void TestSum4() { cout << Sum_Solution4<3>::N << endl; }
相关文章推荐
- 实现1+2+3...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)
- 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。Java实现
- 求1+2+3+...+n,要求不能使用乘除法,for,while,if,else,switch,case等关键字以及条件判断语句
- 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
- C语言奇思妙想:求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case 等关键字以及条件判断语句(A?B:C)
- 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)
- 求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)
- 求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句
- 求1+2+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A? B:C)
- 求1+2+…+n, 要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)。
- 题目:求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)
- 求1+2+3+...+n,要求不能使用乘除法,for,while,if,else,switch,case等关键字以及条件判断语句
- 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)
- PHP 不用求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)
- 求1+2+…+n, 要求不能使用乘除法、for、while、if、else、switch、case等关键字 以及条件判断语句(A?B:C)
- 求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)
- 求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case 等关键字以及条件判断语句
- C/C++学习(一)题目:求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)。
- 题目:求1+2+…+n, 要求不能使用乘除法、for、while、if、else、switch、case 等关键字以及条件判断语句
- 题目:求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)。