• 递归加法(day1)


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

    使用函数指针

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    //使用函数指针 递归加法
    typedef (*fun)(int);
    int func1(int n) {
    return 0;
    }
    int func2(int n) {
    fun f[2] = {func1, func2};
    return n + f[(n != 0)](n - 1);
    }
    void function1() {
    cout << func2(10) << endl;
    }
    //----->fun2 end

    使用静态变量

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    //----->fun2 start
    //使用静态变量
    class test {
    static int N;
    static int sum;
    public :
    test() {
    sum += ++N;
    }
    大专栏  递归加法(day1)lass="function">static void reset() {
    N = sum = 0;
    }
    static int getSum() {
    return sum;
    }
    };
    int test::N = 0;
    int test::sum = 0;
    void function2() {
    test::reset();
    test *p = new test[10];
    cout << test::getSum() << endl;
    delete[]p;
    }
    //--->fun2 end

    使用虚函数的编译多态性

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    //----->fun3 start
    //使用虚函数的编译多态性
    class A {
    public:
    virtual int sum(int n) { return 0; };
    };
    class B : public A {
    public:
    int sum(int n) {
    A a;
    B b;
    A *p[2] = {&a, &b};
    return n + p[(n - 1 != 0)]->sum(n - 1);
    }
    };
    void function3() {
    B b;
    cout << b.sum(10) << endl;
    }
    //----->fun3 end

    源码github

  • 相关阅读:
    2333
    STL string
    后缀自动机的应用
    省选一轮
    等价类计数问题(Polya定理和burnside引理)
    Prufer序列与树的计数(坑)
    分治算法
    生成函数
    莫队算法
    Xamarin 技术解析
  • 原文地址:https://www.cnblogs.com/lijianming180/p/12239740.html
Copyright © 2020-2023  润新知