剑指offer 学习笔记 求1+2+...+n

面试题64:求1+2+…+n。不能用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(包括A?B:C)。

法一:构造函数求解。循环让相同的代码循环运行n次,我们也可以不用循环语句完成,先定义一个类型,接着创建n个该类型的对象,那么这个类型的构造函数就会被调用n次:

#include <iostream>
using namespace std;

class Temp {
public:
    Temp() {
        ++i;
        sum += i;
    }

    static unsigned GetSum() {
        return sum;
    }

    static void Reset() {
        i = 0;
        sum = 0;
    }
private:
    static unsigned i;
    static unsigned sum;
};

unsigned Temp::i = 0;
unsigned Temp::sum = 0;

unsigned GetSum(int n) {
    if (n < 1) {
        return -1;
    }

    Temp::Reset();

    Temp* p = new Temp[n];
    delete[] p;
    p = nullptr;

    return Temp::GetSum();
}

int main() {
    cout << GetSum(5) << endl;
}

法二:虚函数求解。由于我们不能通过if判断来终止递归,我们可以定义两个函数,一个充当递归函数的角色,一个处理终止递归的情况,我们需要做的就是二选一。可以使用bool变量完成二选一,如值为true时调用第一个函数,否则调用第二个。我们可以把数值变量n当做布尔值使用,n非0时,通过!!n使条件为true,n为0时,通过!!n使得条件为false:

#include <iostream>
using namespace std;

class A;
A* arr[2];

class A {
public:
    virtual int GetSum(int n) {
        return 0;
    }
};

class B : public A {
public:
    virtual int GetSum(int n) override {
        return arr[!!n]->GetSum(n - 1) + n;
    }
};

int GetSum(int n) {
    if (n < 1) {
        return 0;
    }

    A a;
    B b;
    arr[0] = &a;
    arr[1] = &b;

    return arr[!!n]->GetSum(n);
}

int main() {
    cout << GetSum(5) << endl;
}

法三:函数指针求解。在纯C环境中,不能用虚函数,可以直接使用函数指针:

#include <iostream>
using namespace std;

int GetSumTeminator(int n) {
    return 0;
}

int GetSum(int n) {
    static int (*p[2])(int) = { GetSumTeminator, GetSum };    // 将两个函数指针存放在static数组中
    return p[!!n](n - 1) + n;
}

int main() {
    cout << GetSum(5) << endl;
}

法四:利用模板类型求解:

template <unsigned int n> struct getSum {
    enum Value { N = getSum<n - 1>::N + n };
};

template <> struct getSum<1> {
    enum Value { N = 1 };
};


int main() {
    getSum<5> res;
    cout << res.N << endl;
}

在编译时,getSum会递归计算和,n必须是编译时就能确定的常量,不能动态输入,且编译器对递归编译代码的深度有限制,不能输入太大的n。

以上代码中使用枚举是因为枚举在类中与static的成员类似,可以不生成对象就访问,并且枚举也不占用类对象的空间,而是相当于常量,在编译期就被替换为值了。这种枚举用法可以用在之前比较老的不支持类内const static的编译器上,因此一种可替代的写法如下:

template <unsigned int n> struct getSum {
    const static unsigned int N = getSum<n - 1>::N + n;
};

template <> struct getSum<1> {
    const static unsigned int N = 1;
};

int main() {
    getSum<5> res;
    cout << res.N << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值