[剑指Offer]求1+2+3+...+n

构造函数使用

Posted by JinFei on December 15, 2019

题目描述

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

解题思路

  • 使用构造函数
  • 设置两个静态变量,当前num,当前sum
  • 每次初始化这个类的一个对象时,当前num自增,然后将sum += num
  • 这样肯定生成的是这个类的对象数组(生成过程可以用指针替代,如Test* test = new Test[n])
  • 注意静态变量的写法
  • 在类中,声明时,static int x;
  • 在类外初始化时,只需要 int Test::x = 0 即可(即不需要再次强调static)(如果强调的话,会编译不过去的)
  • 每次调用之前,记得要初始化(需要可能会有多个测试用例,如果不初始化,下次的结果是上次累加后的结果,显然是错误的)
  • 最后调用delete后,记得要把悬挂指针置为NULL
class Test{
public:
    Test(){
        ++num;
        sum += num;
    }
    static void init(){
        num = 0;
        sum = 0;
    }
    static int getSum(){
        return sum;
    }
 private:
    static int num;
    static int sum;
    
};

int Test::num = 0;
int Test::sum = 0;

class Solution {
public:
    int Sum_Solution(int n) {
        Test::init();
        Test *test = new Test[n];
        delete[] test;
        test = NULL;
        return Test::getSum();
    }
};