zoukankan      html  css  js  c++  java
  • 46 求1+2+3+...+n 静态成员函数和静态变量

    题目描述

    求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
    思路: 1)使用构造函数的方法,需要使用static变量。
        2)虚函数原理
        3)利用函数指针原理
                4)短路原理,使用&&,||
     
     短路原理指的是a && b,如果a为0后面的b就不执行。
    思路1:使用构造函数的方法。新建一个数组,比如new,那么会调用它的构造函数,只要在构造函数里面写一个+=的语句,就可以实现这个累加的功能。
    思路2:使用短路原理,利用&&短路操作,这题限制使用if语句,那么递归基就没法判断,所以利用n && f(n - 1)进行判断,n为0的时候就返回0;
    class Solution {
    public:
        int Sum_Solution(int n) {
            int res = n;
            res && (res += Sum_Solution(n - 1));
            return res;       
        }
    };
     
     
    class tmp{
    public:
        tmp(){
          ++num,sum += num; 
        }
        static void reset(){
            num = 0;
            sum = 0;
        }
        static int getsum(){
            return sum;
        }
    private:
        static int num;
        static int sum;
         
    };
     int tmp::num = 0;
     int tmp::sum = 0;
    class Solution {
    public:  
        int Sum_Solution(int n) {
            tmp::reset();//因为是静态变量,内部使用循环测试,所以必须要清零
            tmp* a = new tmp[n];       
            return tmp::getsum();
        }
    };
     
  • 相关阅读:
    C# 调试
    C#添加资源的两种方式
    C# 光标文件的创建
    窗体初始位置
    C# 实现关闭按钮隐藏窗体而不退出
    mac ssd开启trim模式
    iOS打包上传app store各种问题解决总结
    adhoc无法下载应用程序 此时无法安装-解决
    debug1: expecting SSH2_MSG_KEX_ECDH_REPLY解决
    Could not load OpenSSL解决
  • 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/8269696.html
Copyright © 2011-2022 走看看