要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)
这道题是道好题,何海涛面试100题中提供了如下方法:http://zhedahht.blog.163.com/
1、利用了静态成员变量和构造函数的特点,受教了
#include "iostream" #include <algorithm> #include <functional> using namespace std; class Temp { public: Temp() { ++ N; Sum += N; } static void Reset() { N = 0; Sum = 0; } static int GetSum() { return Sum; } private: static int N; static int Sum; }; int Temp::N = 0; int Temp::Sum = 0; int solution1_Sum(int n) { Temp::Reset(); Temp *a = new Temp[n]; delete []a; a = 0; return Temp::GetSum(); } int main(void){ cout<<solution1_Sum(100); return 0; }
下面的方法都是如何构造递归思想实现的:
2、巧用虚函数,
#include "iostream" #include <algorithm> #include <functional> 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(void){ cout<<solution2_Sum(100); return 0; }
#include "iostream" #include <algorithm> #include <functional> using namespace std; typedef int (*fun)(int); int solution3_f1(int i) { return 0; } int solution3_f2(int i) { fun f[2]={solution3_f1, solution3_f2}; return i+f[!!i](i-1); } int main(void){ cout<<solution3_f2(100); return 0; }
#include "iostream" #include <algorithm> #include <functional> using namespace std; template <int n> struct solution4_Sum { enum Value { N = solution4_Sum<n - 1>::N + n}; }; template <> struct solution4_Sum<1> { enum Value { N = 1}; }; int main(void){ cout<<solution4_Sum<100>().N; return 0; }
还有一种方法,不用这些讨巧的方法依然能够实现1+2+..+n
我们知道1+2+..+n=(n^2+n)/2,n^2最难求
对于n^2,我们可以模拟小学乘法公式的求法,
1010
* 1010
1010
1010
1100100
#include "iostream" #include <algorithm> #include <functional> using namespace std; #define T(X, Y, i) (Y & (1<<i)) && (X+=(Y<<i)) int foo(int n){// (n^2+n)/2 int r=n; //n //n^2 T(r, n, 0);T(r, n, 1);T(r, n, 2);T(r, n, 3);T(r, n, 4); T(r, n, 5);T(r, n, 6);T(r, n, 7);T(r, n, 8);T(r, n, 9); T(r, n, 10);T(r, n, 11);T(r, n, 12);T(r, n, 13);T(r, n, 14); T(r, n, 15);T(r, n, 16);T(r, n, 17);T(r, n, 18);T(r, n, 19); T(r, n, 20);T(r, n, 21);T(r, n, 22);T(r, n, 23);T(r, n, 24); T(r, n, 25);T(r, n, 26);T(r, n, 27);T(r, n, 28);T(r, n, 29); T(r, n, 30);T(r, n, 31); return r >> 1; // /2 } int main(void){ cout<<foo(100); return 0; }