题目描述
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
思路一:利用&&的判断特性(前面false不在判断后面)递归来做;
int Sum_Solution(int n) {
int t = 0;
bool b = (n!=0 && (t = Sum_Solution(n-1)));
return n + t;
}
思路二:利用类的构造函数来做;
class Temp
{
public:
Temp()
{
COUNT++;
SUM+=COUNT;
}
static void Reset()
{
COUNT=0;
SUM=0;
}
static int GetSum()
{
return SUM;
}
private:
static int COUNT;
static int SUM;
};
int Temp::COUNT=0;
int Temp::SUM=0;
class Solution {
public:
int Sum_Solution(int n) {
Temp::Reset();
Temp *a=new Temp[n];
delete a;
a=NULL;
int result =Temp::GetSum();
return result;
}