剑指offer____求1+2+3+...+n

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

解法一:利用位运算求解

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

解法二:利用构造函数求解

class Solution
{
public:
    Solution()
    {
        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 Solution::n = 0;
unsigned int Solution::sum = 0;
unsigned int sum_solution(unsigned int n)
{
    Solution::Reset();
    Solution *s =new Solution[n];
    delete []s;
    return Solution::GetSum();
}

解法三:利用虚函数求解

class A
{
public:
	virtual unsigned int GetSum(unsigned int n, A *arr[])
	{
		return 0;
	}
};
class B:public A
{
public:
	virtual unsigned int GetSum(unsigned int n, A *arr[])
	{
		return arr[!!n]->GetSum(n - 1,arr) + n;
	}
};
int Cal(unsigned int n)
{
	A *arr[2];
	A a;
	B b;
	arr[0] = &a;
	arr[1] = &b;
	int val = arr[1]->GetSum(n, arr);
	return val;
}

解法四:利用函数指针

typedef unsigned int(*fun) (unsigned int);
unsigned int Solution_f(unsigned int n)
{
	return 0;
}
unsigned int Solution(unsigned int n)
{
	static fun f[2] = {Solution_f,Solution};
	return n + f[!!n](n - 1);
}

解法五:利用模板<>

template <unsigned int n> struct solution 
{
	enum Value{N = solution<n-1>::N + n};
};
template <>struct solution<1>
{
	enum Value { N = 1 };
};
int main()
{
	cout << solution<100>::N<< endl;	
	return 0;
}

解法六:用sizeof关键字

const int N = 100;
int cal()
{
	int arr[N][N - 1];
	return sizeof(arr) >> 3;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值