Title: seeking 1 + 2 + 3 + ... + n, requires multiplication and division can not be used, for, while, if, else , switch, case and keywords such as conditional statement (A B:? C).
Solution one:
idea: recursive summation.
class Solution {
public:
int Sum_Solution(int n) {
int sum =n;
sum &&(sum+=Sum_Solution(n-1));
return sum;
}
};
Solution two:
thinking: using the constructor solved. We first define a class, then create instances of the n type, then the constructor will be called n times, we can accumulate code into the constructor function.
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;
class Solution {
public:
int Sum_Solution(int n) {
Temp::Reset();
Temp* a = new Temp[n];
delete[]a;
a = nullptr;
return Temp::GetSum();
}
};
Solution three:
thinking: the use of virtual functions to solve.
class A;
A *Array[2];
class A
{
public:
virtual unsigned int Sum(unsigned int n)
{
return 0;
}
};
class B :public A
{
public:
unsigned int Sum(unsigned int n)
{
return Array[!!n]->Sum(n - 1) + n;
}
};
class Solution {
public:
int Sum_Solution(int n) {
A a;
B b;
Array[0] = &a;
Array[1] = &b;
int value = Array[1]->Sum(n);
return value;
}
};