天天看點

一道很有意思的題目,計算sum

原文來自:http://zhedahht.blog.163.com/blog/static/2541117420072915131422/

我稍微整理了下:

題目是這樣的:計算從1加到n,sum = 1+2+3+...+n,不能用乘除法,for,while,if,else,switch,case等以及條件判斷和?:操作符

經過對文章以及評論的分析,得出如下的一些解法,很有意思,不在于這道題,而在于不同的思路以及對知識的深入了解:

基本上都是代碼,基本都能看得懂的,很短。。。

#include <iostream>
#include <cmath>
using namespace std;

//題目:計算從1加到n,sum = 1+2+3+...+n,不能用乘除法,for,while,if,else,switch,case等以及條件判斷和?:操作服

//方法一:C++對象數組的構造初始化,new n個對象出來,将調用構造函數n次
class Temp {
public:
    Temp() { ++n; sum = 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 solution_one(int n)
{
    Temp::Reset();
    Temp *a = new Temp[n];
    delete []a;
    return Temp::GetSum();
}

//方法二:利用遞歸+虛函數+繼承
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 solution_two(int n)
{
    A a;
    B b;
    array[0] = &a;
    array[1] = &b;
    return array[1]->sum(n);
}

//方法二其實可以不用虛函數,用函數指針同樣可以實作
typedef int (*Fun)(int);

int _solution_two_another(int n)
{
    return 0;
}

int solution_two_another(int n)
{
    Fun f[2] = { _solution_two_another, solution_two_another };
    return n + f[!!n](n-1);
}

//方法三:編譯期間完成,利用enum和模闆程式設計
template <int n>
struct solution_three
{
    enum Value { N = solution_three<n-1>::N + n};
};
template <>
struct solution_three<1>
{
    enum Value { N = 1 };
};

//方法四:遞歸和&&操作服
int solution_four(int n, int &sum)
{
    return n && (sum += n) && solution_four(n-1, sum);
}

//方法五:還是遞歸
int solution_five(int n)
{
    int sum = 0;
    n && ( sum = n + solution_five(n-1) );
    return sum;
}

//方法六:利用數學公式和對數計算法則
int solution_six(int n)
{
    int tmp = exp( log(n) + log(n+1) );
    return  tmp >> 1;
}

int main()
{
    cout << "one : " << solution_one(100) << endl;
    cout << "two : " << solution_two(100) << endl;
    cout << "two another : " << solution_two_another(100) << endl;
    cout << "three : " << solution_three<100>::N << endl;

    int sum = 0;
    solution_four(100, sum);
    cout << "four : " << sum << endl;

    cout << "five : " << solution_five(100) << endl;
    cout << "six : " << solution_six(100) << endl;
    return 0;
}
           

繼續閱讀