面试题46: 使用构造函数和函数指针完成加法求和

1.题目,求1+2+3+......+n,要求不能使用乘除法,for,while,if,else、switch、case等关键字及条件判断语句(A?B:C).
分析:
构造函数的方法,定义一个类型,接着创建该类型的n个实例,则该类型的构造函数会被调用n次,可以将累加的代码放在构造函数里。每次都会被调用。

函数指针的方法,可以采用递归的方法,但是限定了if的使用,递归的进行和终止只能用其他的方法来实现,可以写两个函数,一个用来递归,另一个来终止递归,当适当的时候,选择不同的函数,这就需要一个指示变量,可以用布尔变量,两个不同的取值对应两个不同的函数。将数值n转换成布尔值,可以采用!!n的方式,n非零的时表达式是true,n为0时表达式的值是false。


源码:

/*
 * \file question_46.cpp
 *
 * \author 305
 * \date 十月 2016
 *
 *
 */
#include <iostream>
using namespace std;
// ====================方法一====================
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();
}
// ====================方法二====================
typedef unsigned int(*fun)(unsigned int);
unsigned int Solution2_Teminator(unsigned int n)//终止递归
{
	return 0;
}
unsigned int Sum_Solution2(unsigned int n)//递归
{
	static fun f[2] = { Solution2_Teminator, Sum_Solution2 };
	return n + f[!!n](n - 1);//!!n的含义就是转化成布尔值,调用第一个或者第二个函数指针指向的函数,n大于0时递归,n为0是调用第一个函数终止递归
}
int main()
{
	unsigned int number = 10;
	cout << "----solution 1----" << endl;
	unsigned int result1 = Sum_Solution1(number);
	cout << "the sum of " << number << " is :" << result1 << endl;
	cout << "----solution 2----" << endl;
	unsigned int result2 = Sum_Solution2(number);
	cout << "the sum of " << number << " is :" << result2 << endl;
	system("pause");
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值