zoukankan      html  css  js  c++  java
  • 剑指 offer set 25 求 1+2+...+n

    题目

    要求不能使用乘除法, for, while, if else, switch, case 等关键字

    思路

    1. 循环已经命令禁止, 禁用 if, 意味着递归也不能使用. 但即便如此, 我们仍然要围绕循环或递归作文章

    2. 利用构造函数求解

    #include <iostream>
    using namespace std;
    
    class Temp {
    public:
    	Temp() {
    		++ N; 
    		Sum += N;
    		cout << "constructing " << endl;
    	}
    
    	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;
    
    unsigned int Sum_Solution1(unsigned int n) {
    	Temp::Reset();
    
    	Temp *a = new Temp[n];
    	delete a;
    	a = NULL;
    
    	return Temp::getSum();
    }
    
    int main() {
    	cout << Sum_Solution1(5) << endl;
    	return 0;
    }
    

      

    3. 利用虚函数求解

    #include <iostream>
    using namespace std;
    class A;
    
    A *arr[2];
    
    class A {
    public:
    	virtual unsigned int Sum(unsigned int n) {
    		return 0;
    	}
    };
    
    class B : public A {
    public:
    	virtual unsigned int Sum(unsigned int n) {
    		return arr[!!n]->Sum(n-1) + n;
    	}
    };
    
    int Sum_Solution2(int n) {
    	A a;
    	B b;
    
    	arr[0] = &a, arr[1] = &b;
    
    	int value = arr[1]->Sum(n);
    
    	return value;
    }
    
    int main() {
    	cout << Sum_Solution2(5) << endl;
    	return 0;
    }
    

      

    4. using function point. An alternative to virtual function but much more straightforward

    #include <iostream>
    using namespace std;
    
    typedef unsigned int (*fun) (unsigned int);
    
    unsigned int terminator(unsigned int n) {
    	return 0;
    }
    
    unsigned int solution3(unsigned int n) {
    	static fun f[2] = {terminator, solution3};
    	return n + f[!!n](n-1);
    }
    

      

    总结

    1. !!n 可以将整数转化为 0,1

    2. heavy use of static to attach number to class or function

  • 相关阅读:
    CF 986A Fair——多源bfs
    poj3539 Elevator——同余类bfs
    poj3463 Sightseeing——次短路计数
    poj2262 Goldbach's Conjecture——筛素数
    Kruskal算法
    Prim算法
    离散化
    最短路(hdu2544)
    最短路径问题
    Servlet
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3564182.html
Copyright © 2011-2022 走看看