题目描述:
求 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; }
很酷的名字吧。。这是一个非常酷的技术,能够把计算的时间从运行期提前到编译期。
参考 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 }; };
解法 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;
Interview----求 1+2+...+n, 不能用乘除法、for、while if、else、switch、case 等关键字以及条件判断语句 (A?B:C),布布扣,bubuko.com
Interview----求 1+2+...+n, 不能用乘除法、for、while if、else、switch、case 等关键字以及条件判断语句 (A?B:C)
原文:http://blog.csdn.net/shoulinjun/article/details/20564095