题目描述
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
思路一:采用函数递归,return n + f(n - 1);用n的数值和&&运算作为判断条件;
代码一:
class Solution {
public:
int Sum_Solution(int n) {
int sum = n;
n && (sum += Sum_Solution(n - 1));
return sum;
}
};
思路二:当然,还有一种奇葩的解法,利用sizeof()函数和>>操作实现乘法和除法。
代码二:
class Solution {
public:
int Sum_Solution(int n) {
char helper[n][n+1];
return (sizeof(helper) >> 1);
}
};
思路三:使用类的构造函数,用多次定义类变量,从而多次执行构造函数,进而实现多次累加。
代码三:
class Tmp {
public:
Tmp() {
++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 Tmp::N;
unsigned int Tmp::Sum;
class Solution {
public:
int Sum_Solution(int n) {
Tmp::Reset();
Tmp* a = new Tmp[n]; //申请内存空间
delete [] a; //释放内存空间,防止内存泄漏
a = NULL; //让a从指向不存在空间的野指针变为NULL,防止后面使用a时出错
return Tmp::Getsum();
}
};