剑指Offer 1+2+...+n 构造函数法实现

来源:互联网 发布:淘宝助理免费吗 编辑:程序博客网 时间:2024/06/07 12:04

不准用乘除法、for、while、if、else、switch、case及A?B:C
在终端跳转到源文件的当前目录后,输入

g++ 1to100constructed.cpp -o 1to100constructed1to100constructed 100

即可在终端得1+2+…+100的结果

//file name"1to100constructed.cpp"#include <cstddef>#include <iostream>#include <sstream>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;int main(int argc,char *argv[]){    int Number;    std::stringstream stream;    stream << argv[1];    stream >> Number;    unsigned int result = 0;    Temp::Reset();    Temp *a = new Temp[Number];    delete []a;    a = NULL;    result = Temp::GetSum();    std::cout << result << std::endl;    system("pause");    return 1;}
0 0
原创粉丝点击