求1+2+...+n 【微软面试100题 第十二题】

题目要求:

  要求不能使用乘除法,for/while/if/else/switch/case等关键字以及条件判断语句(A?B:C)。

  参考资料:剑指offer第46题

题目分析:

  方法1:利用类的静态成员变量,定义一次之后该类的所有对象都共享该静态成员变量。再利用构造函数实现n次递加即可;

  方法2:利用函数指针;

  方法3:利用虚函数和动态联编(虚函数和动态联编介绍:http://blog.csdn.net/qlping2007/article/details/2177880).

代码实现:

  方法1代码:

#include <iostream>



using namespace std;



class Temp

{

public:

    Temp(){++N;Sum += N;}

    ~Temp(){}

    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;



int main(void)

{

    int n = 10;



    Temp::Reset();

    Temp *a = new Temp[n];

    delete []a;

    a = NULL;



    cout << Temp::getSum() << endl;

    

    return 0;

}
View Code  

  方法2代码:

#include <iostream>



using namespace std;



typedef unsigned int (*fun)(unsigned int);

unsigned int f2(unsigned int n);



int main(void)

{

    cout << f2(10) << endl;

    return 0;

}

unsigned int f1(unsigned int n)

{

    return 0;

}

unsigned int f2(unsigned int n)

{

    fun f[] = {f1,f2};



    return n+f[!!n](n-1);

}
View Code

  方法3代码:

#include <iostream>



using namespace std;



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 sumSolution(int n);



int main(void)

{

    cout << sumSolution(10) << endl;

    return 0;

}

int sumSolution(int n)

{

    A a;

    B b;

    Array[0] = &a;

    Array[1] = &b;



    int value = Array[1]->Sum(n);

    return value;

}
View Code

你可能感兴趣的:(面试)