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

题目描述:

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


分析:

首先想到的是写递归函数,但是遇到一个问题,递归函数总需要一个出口,不然会无穷递归下去。

出口一半是 if() return. 题目又要求不能使用 if 语句。

什么语句有类似与 if 的选择功能呢??


解法 1: || 运算符号

A || B 有如下性质: 当 A 是 true 时, B 语句不再运行。。这里就包含了 选择的功能。

// Method 2: recursive function
int Sum(int n)
{
  int ret = 0;
  n == 0 || (ret = Sum(n-1));
  return n + ret;
}

解法 2: 模板元编程 TMP

很酷的名字吧。。这是一个非常酷的技术,能够把计算的时间从运行期提前到编译期。

参考 Effective C++。

其实思想就是 利用函数模板的特化(specialization),来模拟 选择语句。

// Method 1: TMP, reference: Effective C++
template<unsigned n>
struct MySum{
  enum { value = MySum<n-1>::value + n };
};

// use template specialization to mimic if expression
template<>
struct MySum<0>{
  enum { value = 0 };
};

MySum<10>::value 就是我们要的结果。。


解法 3:

采用C++ 类中的 static 变量,已经构造函数在对象构造时会被自动调用的性质。

// Method 3: static variable of class
struct MyClass{
  MyClass(){
    sum += ++ n;
  }
  static int n; 
  static int sum;
};
// static members should be defined outside class body
int MyClass::n = 0;
int MyClass::sum = 0;

  MyClass a[10];
  cout << MyClass::sum << endl;



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值