剑指Offer-64:求1+2+...+n

题目:

求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

链接:

剑指Offer(第2版):P307

思路标签:

  • 构造函数虚函数函数指针逻辑与的短路特性

解答:

1. 书上的四种解法就不一一列举了

  • 这里仅直接列出相关的前三种解法
//构造函数
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);
}

2. 给出关于逻辑与的短路性质方法:

class Solution {
public:
    int Sum_Solution(int n) {
    int sum = n;
    bool ans = (n>0)&&((sum+=Sum_Solution(n-1))>0);
    return sum;
    }
};

你可能感兴趣的:(剑指Offer,剑指Offer,笔试面试,编程题)