求1+2+3+...+n

题目

  求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

思路

  1.先定义一个该类型,在创建n个该类型的实例,那么这个类型的构造函数被调用n次,将累加的相关代码放到构造函数中,这涉及到对象间的变量共享,用static静态成员变量。

#include <iostream>
using namespace std;
//因为共用数据,则需要使用静态成员和静态方法 
class Solution
{
    private:
        static unsigned int n;//static const int可以在类中初始化,类中声明,类外定义 
        static unsigned int sum;
    public:
        Solution();
        static void rest();
        static unsigned int get_sum();//静态成员函数只能访问静态成员变量,静态成员函数 
};
unsigned int Solution::n=0;//初始化静态成员变量要在类的外面进行,不能用参数初始化表,对静态成员变量进行初始化
unsigned int Solution::sum=0;
Solution::Solution()
{
    ++n;
    sum+=n;
}
void Solution::rest()
{
    Solution::n=0;
    Solution::sum=0;
}
unsigned int Solution::get_sum()
{
    return sum;
}

int main()
{
    Solution *s=new Solution[3];
    delete []s;
    s=nullptr;
    cout<<Solution::get_sum()<<endl;
    
    return 0;
}

  2.利用逻辑与,A && B,如果A为false,则不会判断B。这一特性可以用来结束递归。n>0时, 计算 sum+=getSum(n-1) ,n=0时,不满足n>0,&&后面的表达式不会执行,结束递归,return sum。

#include <iostream>
using namespace std;

class Solution
{
    public:
        unsigned int get_sum(const unsigned int n);
};
unsigned int Solution::get_sum(const unsigned int n)
{
    int sum=n;
    bool flag=(n>0)&&((sum+=get_sum(n-1))>0);
    return sum;
}
int main()
{
    Solution s;
    cout<<s.get_sum(3)<<endl;
    return 0;
}

   3.定义两个函数充当递归的角色,一个是递归调用,一个是终止递归,从这两个函数中二选一,对n两次取反操作,可以把n变成布尔类型的值

    当n为0时调用A::get_sum,否则调用B::get_sum.

#include <iostream>
using namespace std;

class A;
A *array[2];
class A
{
    public:
        virtual unsigned int get_sum(unsigned int n)
        {
            return 0;    
        } 
};
class B:public A
{
    public:
        virtual unsigned int get_sum(unsigned int n)
        {
            return array[!!n]->get_sum(n-1)+n;
        }
};
int main()
{
    A a;
    B b;
    array[0]=&a;
    array[1]=&b;
    int sum=array[1]->get_sum(3);
    cout<<sum<<endl;    
    return 0;
}

   4.利用函数指针求解

#include <iostream>
using namespace std;

typedef unsigned int (*fun)(unsigned int n);

unsigned int f1(unsigned int n)
{
    return 0;
}
unsigned int f2(unsigned int n)
{
    fun f[2]={f1,f2};
    return n+f[!!n](n-1);
}
int main()
{
    cout<<f2(3)<<endl;
    return 0;
}

   5.利用函数模板,solution<3>会以参数3生成该类型的代码,但以3为类型的参数需要得到以99为参数类型,因为N=Solution<n-1>::N+3,这个过程会一直递归到以参数1为类型。由于整个过程是编译过程中完成的,要求n在编译时确定的常量,不能动态输入,而且,递归时n不能太大。

#include <iostream>
using namespace std;

template <unsigned int n>
class Solution
{
    public:
        enum value//枚举变量在编译时可区分类型 
        {
            N=Solution<n-1>::N+n
        };    
};
template <>
class Solution<1>
{
    public:
        enum value
        {
            N=1
        };
};
int main()
{
    cout<<Solution<3>::N<<endl;
    return 0;
} 

 code

class Solution {
public:
    int Sum_Solution(int n) {
        if(n==0||n==1)
            return n;
        
        char arr[n][n+1];//n*(n+1)
        return sizeof(arr)>>1;
    }
};
原文地址:https://www.cnblogs.com/tianzeng/p/10325972.html