剑指offer:求1+2+3+...+n

题目描述

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

方法一:构造函数

class helper {
public:

    helper(){
        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 helper::n = 0;
unsigned int helper::sum = 0;


class Solution {
public:
    int Sum_Solution(int n) {
        helper::reset();

        helper *s = new helper[n];

        int res = helper::getSum();

        delete[]s;

        return res;
    }
};

方法二:虚函数

class base;
base * array[2];

class base{
public:
    virtual unsigned int sum(unsigned int n){
        return 0;
    }
};

class derive :public base{
public:
    virtual unsigned int sum(unsigned int n){
        return array[!!n]->sum(n - 1) + n;
    }
};


class Solution {
public:
    int Sum_Solution(int n) {

        base a;
        derive b;

        array[0] = &a;
        array[1] = &b;

        return b.sum(n);
    }
};


int main(){

    Solution s;

    cout<<s.Sum_Solution(10);

    return 0;
}

方法三:函数指针

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

unsigned int teminator(unsigned int n){
    return 0;
}

unsigned int recursion(unsigned int n){
    static fun f[2] = { teminator, recursion };

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

方法四:短路特征

class Solution {
public:
    int Sum_Solution(int n) {
        int res = n;
        res && (res += Sum_Solution(n - 1));

        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值