求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
解法一:利用位运算求解
class Solution {
public:
int Sum_Solution(int n) {
int sum = n;
sum && (sum += Sum_Solution(n - 1));
return sum;
}
};
解法二:利用构造函数求解
class Solution
{
public:
Solution()
{
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 Solution::n = 0;
unsigned int Solution::sum = 0;
unsigned int sum_solution(unsigned int n)
{
Solution::Reset();
Solution *s =new Solution[n];
delete []s;
return Solution::GetSum();
}
解法三:利用虚函数求解
class A
{
public:
virtual unsigned int GetSum(unsigned int n, A *arr[])
{
return 0;
}
};
class B:public A
{
public:
virtual unsigned int GetSum(unsigned int n, A *arr[])
{
return arr[!!n]->GetSum(n - 1,arr) + n;
}
};
int Cal(unsigned int n)
{
A *arr[2];
A a;
B b;
arr[0] = &a;
arr[1] = &b;
int val = arr[1]->GetSum(n, arr);
return val;
}
解法四:利用函数指针
typedef unsigned int(*fun) (unsigned int);
unsigned int Solution_f(unsigned int n)
{
return 0;
}
unsigned int Solution(unsigned int n)
{
static fun f[2] = {Solution_f,Solution};
return n + f[!!n](n - 1);
}
解法五:利用模板<>
template <unsigned int n> struct solution
{
enum Value{N = solution<n-1>::N + n};
};
template <>struct solution<1>
{
enum Value { N = 1 };
};
int main()
{
cout << solution<100>::N<< endl;
return 0;
}
解法六:用sizeof关键字
const int N = 100;
int cal()
{
int arr[N][N - 1];
return sizeof(arr) >> 3;
}